Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/config_backend.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_config_file_h__ #define INCLUDE_config_file_h__ #include "common.h" #include "git2/sys/config.h" #include "git2/config.h" /** * Create a configuration file backend for ondisk files * * These are the normal `.gitconfig` files that Core Git * processes. Note that you first have to add this file to a * configuration object before you can query it for configuration * variables. * * @param out the new backend * @param path where the config file is located */ extern int git_config_backend_from_file(git_config_backend **out, const char *path); /** * Create a readonly configuration file backend from another backend * * This copies the complete contents of the source backend to the * new backend. The new backend will be completely read-only and * cannot be modified. * * @param out the new snapshotted backend * @param source the backend to copy */ extern int git_config_backend_snapshot(git_config_backend **out, git_config_backend *source); /** * Create an in-memory configuration file backend * * @param out the new backend * @param cfg the configuration that is to be parsed * @param len the length of the string pointed to by `cfg` */ extern int git_config_backend_from_string(git_config_backend **out, const char *cfg, size_t len); GIT_INLINE(int) git_config_backend_open(git_config_backend *cfg, unsigned int level, const git_repository *repo) { return cfg->open(cfg, level, repo); } GIT_INLINE(void) git_config_backend_free(git_config_backend *cfg) { if (cfg) cfg->free(cfg); } GIT_INLINE(int) git_config_backend_get_string( git_config_entry **out, git_config_backend *cfg, const char *name) { return cfg->get(cfg, name, out); } GIT_INLINE(int) git_config_backend_set_string( git_config_backend *cfg, const char *name, const char *value) { return cfg->set(cfg, name, value); } GIT_INLINE(int) git_config_backend_delete( git_config_backend *cfg, const char *name) { return cfg->del(cfg, name); } GIT_INLINE(int) git_config_backend_foreach( git_config_backend *cfg, int (*fn)(const git_config_entry *entry, void *data), void *data) { return git_config_backend_foreach_match(cfg, NULL, fn, data); } GIT_INLINE(int) git_config_backend_lock(git_config_backend *cfg) { return cfg->lock(cfg); } GIT_INLINE(int) git_config_backend_unlock(git_config_backend *cfg, int success) { return cfg->unlock(cfg, success); } #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/object.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_object_h__ #define INCLUDE_object_h__ #include "common.h" #include "repository.h" #define GIT_OBJECT_SIZE_MAX UINT64_MAX extern bool git_object__strict_input_validation; /** Base git object for inheritance */ struct git_object { git_cached_obj cached; git_repository *repo; }; /* fully free the object; internal method, DO NOT EXPORT */ void git_object__free(void *object); /* * Parse object from raw data. Note that the resulting object is * tied to the lifetime of the data, as some objects simply point * into it. */ int git_object__from_raw( git_object **object_out, const char *data, size_t size, git_object_t type); int git_object__from_odb_object( git_object **object_out, git_repository *repo, git_odb_object *odb_obj, git_object_t type); int git_object__resolve_to_type(git_object **obj, git_object_t type); git_object_t git_object_stringn2type(const char *str, size_t len); int git_oid__parse(git_oid *oid, const char **buffer_out, const char *buffer_end, const char *header); void git_oid__writebuf(git_buf *buf, const char *header, const git_oid *oid); bool git_object__is_valid( git_repository *repo, const git_oid *id, git_object_t expected_type); GIT_INLINE(git_object_t) git_object__type_from_filemode(git_filemode_t mode) { switch (mode) { case GIT_FILEMODE_TREE: return GIT_OBJECT_TREE; case GIT_FILEMODE_COMMIT: return GIT_OBJECT_COMMIT; case GIT_FILEMODE_BLOB: case GIT_FILEMODE_BLOB_EXECUTABLE: case GIT_FILEMODE_LINK: return GIT_OBJECT_BLOB; default: return GIT_OBJECT_INVALID; } } #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/patch.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "patch.h" #include "git2/patch.h" #include "diff.h" int git_patch__invoke_callbacks( git_patch *patch, git_diff_file_cb file_cb, git_diff_binary_cb binary_cb, git_diff_hunk_cb hunk_cb, git_diff_line_cb line_cb, void *payload) { int error = 0; uint32_t i, j; if (file_cb) error = file_cb(patch->delta, 0, payload); if (error) return error; if ((patch->delta->flags & GIT_DIFF_FLAG_BINARY) != 0) { if (binary_cb) error = binary_cb(patch->delta, &patch->binary, payload); return error; } if (!hunk_cb && !line_cb) return error; for (i = 0; !error && i < git_array_size(patch->hunks); ++i) { git_patch_hunk *h = git_array_get(patch->hunks, i); if (hunk_cb) error = hunk_cb(patch->delta, &h->hunk, payload); if (!line_cb) continue; for (j = 0; !error && j < h->line_count; ++j) { git_diff_line *l = git_array_get(patch->lines, h->line_start + j); error = line_cb(patch->delta, &h->hunk, l, payload); } } return error; } size_t git_patch_size( git_patch *patch, int include_context, int include_hunk_headers, int include_file_headers) { size_t out; GIT_ASSERT_ARG(patch); out = patch->content_size; if (!include_context) out -= patch->context_size; if (include_hunk_headers) out += patch->header_size; if (include_file_headers) { git_buf file_header = GIT_BUF_INIT; if (git_diff_delta__format_file_header( &file_header, patch->delta, NULL, NULL, 0, true) < 0) git_error_clear(); else out += git_buf_len(&file_header); git_buf_dispose(&file_header); } return out; } int git_patch_line_stats( size_t *total_ctxt, size_t *total_adds, size_t *total_dels, const git_patch *patch) { size_t totals[3], idx; memset(totals, 0, sizeof(totals)); for (idx = 0; idx < git_array_size(patch->lines); ++idx) { git_diff_line *line = git_array_get(patch->lines, idx); if (!line) continue; switch (line->origin) { case GIT_DIFF_LINE_CONTEXT: totals[0]++; break; case GIT_DIFF_LINE_ADDITION: totals[1]++; break; case GIT_DIFF_LINE_DELETION: totals[2]++; break; default: /* diff --stat and --numstat don't count EOFNL marks because * they will always be paired with a ADDITION or DELETION line. */ break; } } if (total_ctxt) *total_ctxt = totals[0]; if (total_adds) *total_adds = totals[1]; if (total_dels) *total_dels = totals[2]; return 0; } const git_diff_delta *git_patch_get_delta(const git_patch *patch) { GIT_ASSERT_ARG_WITH_RETVAL(patch, NULL); return patch->delta; } size_t git_patch_num_hunks(const git_patch *patch) { GIT_ASSERT_ARG(patch); return git_array_size(patch->hunks); } static int patch_error_outofrange(const char *thing) { git_error_set(GIT_ERROR_INVALID, "patch %s index out of range", thing); return GIT_ENOTFOUND; } int git_patch_get_hunk( const git_diff_hunk **out, size_t *lines_in_hunk, git_patch *patch, size_t hunk_idx) { git_patch_hunk *hunk; GIT_ASSERT_ARG(patch); hunk = git_array_get(patch->hunks, hunk_idx); if (!hunk) { if (out) *out = NULL; if (lines_in_hunk) *lines_in_hunk = 0; return patch_error_outofrange("hunk"); } if (out) *out = &hunk->hunk; if (lines_in_hunk) *lines_in_hunk = hunk->line_count; return 0; } int git_patch_num_lines_in_hunk(const git_patch *patch, size_t hunk_idx) { git_patch_hunk *hunk; GIT_ASSERT_ARG(patch); if (!(hunk = git_array_get(patch->hunks, hunk_idx))) return patch_error_outofrange("hunk"); return (int)hunk->line_count; } int git_patch_get_line_in_hunk( const git_diff_line **out, git_patch *patch, size_t hunk_idx, size_t line_of_hunk) { git_patch_hunk *hunk; git_diff_line *line; GIT_ASSERT_ARG(patch); if (!(hunk = git_array_get(patch->hunks, hunk_idx))) { if (out) *out = NULL; return patch_error_outofrange("hunk"); } if (line_of_hunk >= hunk->line_count || !(line = git_array_get( patch->lines, hunk->line_start + line_of_hunk))) { if (out) *out = NULL; return patch_error_outofrange("line"); } if (out) *out = line; return 0; } git_repository *git_patch_owner(const git_patch *patch) { return patch->repo; } int git_patch_from_diff(git_patch **out, git_diff *diff, size_t idx) { GIT_ASSERT_ARG(out); GIT_ASSERT_ARG(diff); GIT_ASSERT_ARG(diff->patch_fn); return diff->patch_fn(out, diff, idx); } static void git_patch__free(git_patch *patch) { if (patch->free_fn) patch->free_fn(patch); } void git_patch_free(git_patch *patch) { if (patch) GIT_REFCOUNT_DEC(patch, git_patch__free); }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/netops.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "netops.h" #include <ctype.h> #include "git2/errors.h" #include "posix.h" #include "buffer.h" #include "http_parser.h" #include "runtime.h" int gitno_recv(gitno_buffer *buf) { return buf->recv(buf); } void gitno_buffer_setup_callback( gitno_buffer *buf, char *data, size_t len, int (*recv)(gitno_buffer *buf), void *cb_data) { memset(data, 0x0, len); buf->data = data; buf->len = len; buf->offset = 0; buf->recv = recv; buf->cb_data = cb_data; } static int recv_stream(gitno_buffer *buf) { git_stream *io = (git_stream *) buf->cb_data; size_t readlen = buf->len - buf->offset; ssize_t ret; readlen = min(readlen, INT_MAX); ret = git_stream_read(io, buf->data + buf->offset, (int)readlen); if (ret < 0) return -1; buf->offset += ret; return (int)ret; } void gitno_buffer_setup_fromstream(git_stream *st, gitno_buffer *buf, char *data, size_t len) { memset(data, 0x0, len); buf->data = data; buf->len = len; buf->offset = 0; buf->recv = recv_stream; buf->cb_data = st; } /* Consume up to ptr and move the rest of the buffer to the beginning */ int gitno_consume(gitno_buffer *buf, const char *ptr) { size_t consumed; GIT_ASSERT(ptr - buf->data >= 0); GIT_ASSERT(ptr - buf->data <= (int) buf->len); consumed = ptr - buf->data; memmove(buf->data, ptr, buf->offset - consumed); memset(buf->data + buf->offset, 0x0, buf->len - buf->offset); buf->offset -= consumed; return 0; } /* Consume const bytes and move the rest of the buffer to the beginning */ void gitno_consume_n(gitno_buffer *buf, size_t cons) { memmove(buf->data, buf->data + cons, buf->len - buf->offset); memset(buf->data + cons, 0x0, buf->len - buf->offset); buf->offset -= cons; } /* Match host names according to RFC 2818 rules */ int gitno__match_host(const char *pattern, const char *host) { for (;;) { char c = git__tolower(*pattern++); if (c == '\0') return *host ? -1 : 0; if (c == '*') { c = *pattern; /* '*' at the end matches everything left */ if (c == '\0') return 0; /* * We've found a pattern, so move towards the next matching * char. The '.' is handled specially because wildcards aren't * allowed to cross subdomains. */ while(*host) { char h = git__tolower(*host); if (c == h) return gitno__match_host(pattern, host++); if (h == '.') return gitno__match_host(pattern, host); host++; } return -1; } if (c != git__tolower(*host++)) return -1; } return -1; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/bitvec.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_bitvec_h__ #define INCLUDE_bitvec_h__ #include "common.h" /* * This is a silly little fixed length bit vector type that will store * vectors of 64 bits or less directly in the structure and allocate * memory for vectors longer than 64 bits. You can use the two versions * transparently through the API and avoid heap allocation completely when * using a short bit vector as a result. */ typedef struct { size_t length; union { uint64_t *words; uint64_t bits; } u; } git_bitvec; GIT_INLINE(int) git_bitvec_init(git_bitvec *bv, size_t capacity) { memset(bv, 0x0, sizeof(*bv)); if (capacity >= 64) { bv->length = (capacity / 64) + 1; bv->u.words = git__calloc(bv->length, sizeof(uint64_t)); if (!bv->u.words) return -1; } return 0; } #define GIT_BITVEC_MASK(BIT) ((uint64_t)1 << (BIT % 64)) #define GIT_BITVEC_WORD(BV, BIT) (BV->length ? &BV->u.words[BIT / 64] : &BV->u.bits) GIT_INLINE(void) git_bitvec_set(git_bitvec *bv, size_t bit, bool on) { uint64_t *word = GIT_BITVEC_WORD(bv, bit); uint64_t mask = GIT_BITVEC_MASK(bit); if (on) *word |= mask; else *word &= ~mask; } GIT_INLINE(bool) git_bitvec_get(git_bitvec *bv, size_t bit) { uint64_t *word = GIT_BITVEC_WORD(bv, bit); return (*word & GIT_BITVEC_MASK(bit)) != 0; } GIT_INLINE(void) git_bitvec_clear(git_bitvec *bv) { if (!bv->length) bv->u.bits = 0; else memset(bv->u.words, 0x0, bv->length * sizeof(uint64_t)); } GIT_INLINE(void) git_bitvec_free(git_bitvec *bv) { if (bv->length) git__free(bv->u.words); } #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/libgit2.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "libgit2.h" #include <git2.h> #include "alloc.h" #include "cache.h" #include "common.h" #include "filter.h" #include "hash.h" #include "index.h" #include "merge_driver.h" #include "pool.h" #include "mwindow.h" #include "object.h" #include "odb.h" #include "refs.h" #include "runtime.h" #include "sysdir.h" #include "thread.h" #include "threadstate.h" #include "git2/global.h" #include "streams/registry.h" #include "streams/mbedtls.h" #include "streams/openssl.h" #include "transports/smart.h" #include "transports/http.h" #include "transports/ssh.h" #ifdef GIT_WIN32 # include "win32/w32_leakcheck.h" #endif /* Declarations for tuneable settings */ extern size_t git_mwindow__window_size; extern size_t git_mwindow__mapped_limit; extern size_t git_mwindow__file_limit; extern size_t git_indexer__max_objects; extern bool git_disable_pack_keep_file_checks; extern int git_odb__packed_priority; extern int git_odb__loose_priority; char *git__user_agent; char *git__ssl_ciphers; static void libgit2_settings_global_shutdown(void) { git__free(git__user_agent); git__free(git__ssl_ciphers); git_repository__free_extensions(); } static int git_libgit2_settings_global_init(void) { return git_runtime_shutdown_register(libgit2_settings_global_shutdown); } int git_libgit2_init(void) { static git_runtime_init_fn init_fns[] = { #ifdef GIT_WIN32 git_win32_leakcheck_global_init, #endif git_allocator_global_init, git_threadstate_global_init, git_threads_global_init, git_hash_global_init, git_sysdir_global_init, git_filter_global_init, git_merge_driver_global_init, git_transport_ssh_global_init, git_stream_registry_global_init, git_openssl_stream_global_init, git_mbedtls_stream_global_init, git_mwindow_global_init, git_pool_global_init, git_libgit2_settings_global_init }; return git_runtime_init(init_fns, ARRAY_SIZE(init_fns)); } int git_libgit2_init_count(void) { return git_runtime_init_count(); } int git_libgit2_shutdown(void) { return git_runtime_shutdown(); } int git_libgit2_version(int *major, int *minor, int *rev) { *major = LIBGIT2_VER_MAJOR; *minor = LIBGIT2_VER_MINOR; *rev = LIBGIT2_VER_REVISION; return 0; } int git_libgit2_features(void) { return 0 #ifdef GIT_THREADS | GIT_FEATURE_THREADS #endif #ifdef GIT_HTTPS | GIT_FEATURE_HTTPS #endif #if defined(GIT_SSH) | GIT_FEATURE_SSH #endif #if defined(GIT_USE_NSEC) | GIT_FEATURE_NSEC #endif ; } static int config_level_to_sysdir(int *out, int config_level) { switch (config_level) { case GIT_CONFIG_LEVEL_SYSTEM: *out = GIT_SYSDIR_SYSTEM; return 0; case GIT_CONFIG_LEVEL_XDG: *out = GIT_SYSDIR_XDG; return 0; case GIT_CONFIG_LEVEL_GLOBAL: *out = GIT_SYSDIR_GLOBAL; return 0; case GIT_CONFIG_LEVEL_PROGRAMDATA: *out = GIT_SYSDIR_PROGRAMDATA; return 0; default: break; } git_error_set( GIT_ERROR_INVALID, "invalid config path selector %d", config_level); return -1; } const char *git_libgit2__user_agent(void) { return git__user_agent; } const char *git_libgit2__ssl_ciphers(void) { return git__ssl_ciphers; } int git_libgit2_opts(int key, ...) { int error = 0; va_list ap; va_start(ap, key); switch (key) { case GIT_OPT_SET_MWINDOW_SIZE: git_mwindow__window_size = va_arg(ap, size_t); break; case GIT_OPT_GET_MWINDOW_SIZE: *(va_arg(ap, size_t *)) = git_mwindow__window_size; break; case GIT_OPT_SET_MWINDOW_MAPPED_LIMIT: git_mwindow__mapped_limit = va_arg(ap, size_t); break; case GIT_OPT_GET_MWINDOW_MAPPED_LIMIT: *(va_arg(ap, size_t *)) = git_mwindow__mapped_limit; break; case GIT_OPT_SET_MWINDOW_FILE_LIMIT: git_mwindow__file_limit = va_arg(ap, size_t); break; case GIT_OPT_GET_MWINDOW_FILE_LIMIT: *(va_arg(ap, size_t *)) = git_mwindow__file_limit; break; case GIT_OPT_GET_SEARCH_PATH: { int sysdir = va_arg(ap, int); git_buf *out = va_arg(ap, git_buf *); const git_buf *tmp; int level; if ((error = config_level_to_sysdir(&level, sysdir)) < 0 || (error = git_buf_sanitize(out)) < 0 || (error = git_sysdir_get(&tmp, level)) < 0) break; error = git_buf_sets(out, tmp->ptr); } break; case GIT_OPT_SET_SEARCH_PATH: { int level; if ((error = config_level_to_sysdir(&level, va_arg(ap, int))) >= 0) error = git_sysdir_set(level, va_arg(ap, const char *)); } break; case GIT_OPT_SET_CACHE_OBJECT_LIMIT: { git_object_t type = (git_object_t)va_arg(ap, int); size_t size = va_arg(ap, size_t); error = git_cache_set_max_object_size(type, size); break; } case GIT_OPT_SET_CACHE_MAX_SIZE: git_cache__max_storage = va_arg(ap, ssize_t); break; case GIT_OPT_ENABLE_CACHING: git_cache__enabled = (va_arg(ap, int) != 0); break; case GIT_OPT_GET_CACHED_MEMORY: *(va_arg(ap, ssize_t *)) = git_cache__current_storage.val; *(va_arg(ap, ssize_t *)) = git_cache__max_storage; break; case GIT_OPT_GET_TEMPLATE_PATH: { git_buf *out = va_arg(ap, git_buf *); const git_buf *tmp; if ((error = git_buf_sanitize(out)) < 0 || (error = git_sysdir_get(&tmp, GIT_SYSDIR_TEMPLATE)) < 0) break; error = git_buf_sets(out, tmp->ptr); } break; case GIT_OPT_SET_TEMPLATE_PATH: error = git_sysdir_set(GIT_SYSDIR_TEMPLATE, va_arg(ap, const char *)); break; case GIT_OPT_SET_SSL_CERT_LOCATIONS: #ifdef GIT_OPENSSL { const char *file = va_arg(ap, const char *); const char *path = va_arg(ap, const char *); error = git_openssl__set_cert_location(file, path); } #elif defined(GIT_MBEDTLS) { const char *file = va_arg(ap, const char *); const char *path = va_arg(ap, const char *); error = git_mbedtls__set_cert_location(file, path); } #else git_error_set(GIT_ERROR_SSL, "TLS backend doesn't support certificate locations"); error = -1; #endif break; case GIT_OPT_SET_USER_AGENT: git__free(git__user_agent); git__user_agent = git__strdup(va_arg(ap, const char *)); if (!git__user_agent) { git_error_set_oom(); error = -1; } break; case GIT_OPT_ENABLE_STRICT_OBJECT_CREATION: git_object__strict_input_validation = (va_arg(ap, int) != 0); break; case GIT_OPT_ENABLE_STRICT_SYMBOLIC_REF_CREATION: git_reference__enable_symbolic_ref_target_validation = (va_arg(ap, int) != 0); break; case GIT_OPT_SET_SSL_CIPHERS: #if (GIT_OPENSSL || GIT_MBEDTLS) { git__free(git__ssl_ciphers); git__ssl_ciphers = git__strdup(va_arg(ap, const char *)); if (!git__ssl_ciphers) { git_error_set_oom(); error = -1; } } #else git_error_set(GIT_ERROR_SSL, "TLS backend doesn't support custom ciphers"); error = -1; #endif break; case GIT_OPT_GET_USER_AGENT: { git_buf *out = va_arg(ap, git_buf *); if ((error = git_buf_sanitize(out)) < 0) break; error = git_buf_sets(out, git__user_agent); } break; case GIT_OPT_ENABLE_OFS_DELTA: git_smart__ofs_delta_enabled = (va_arg(ap, int) != 0); break; case GIT_OPT_ENABLE_FSYNC_GITDIR: git_repository__fsync_gitdir = (va_arg(ap, int) != 0); break; case GIT_OPT_GET_WINDOWS_SHAREMODE: #ifdef GIT_WIN32 *(va_arg(ap, unsigned long *)) = git_win32__createfile_sharemode; #endif break; case GIT_OPT_SET_WINDOWS_SHAREMODE: #ifdef GIT_WIN32 git_win32__createfile_sharemode = va_arg(ap, unsigned long); #endif break; case GIT_OPT_ENABLE_STRICT_HASH_VERIFICATION: git_odb__strict_hash_verification = (va_arg(ap, int) != 0); break; case GIT_OPT_SET_ALLOCATOR: error = git_allocator_setup(va_arg(ap, git_allocator *)); break; case GIT_OPT_ENABLE_UNSAVED_INDEX_SAFETY: git_index__enforce_unsaved_safety = (va_arg(ap, int) != 0); break; case GIT_OPT_SET_PACK_MAX_OBJECTS: git_indexer__max_objects = va_arg(ap, size_t); break; case GIT_OPT_GET_PACK_MAX_OBJECTS: *(va_arg(ap, size_t *)) = git_indexer__max_objects; break; case GIT_OPT_DISABLE_PACK_KEEP_FILE_CHECKS: git_disable_pack_keep_file_checks = (va_arg(ap, int) != 0); break; case GIT_OPT_ENABLE_HTTP_EXPECT_CONTINUE: git_http__expect_continue = (va_arg(ap, int) != 0); break; case GIT_OPT_SET_ODB_PACKED_PRIORITY: git_odb__packed_priority = va_arg(ap, int); break; case GIT_OPT_SET_ODB_LOOSE_PRIORITY: git_odb__loose_priority = va_arg(ap, int); break; case GIT_OPT_SET_EXTENSIONS: { const char **extensions = va_arg(ap, const char **); size_t len = va_arg(ap, size_t); error = git_repository__set_extensions(extensions, len); } break; case GIT_OPT_GET_EXTENSIONS: { git_strarray *out = va_arg(ap, git_strarray *); char **extensions; size_t len; if ((error = git_repository__extensions(&extensions, &len)) < 0) break; out->strings = extensions; out->count = len; } break; default: git_error_set(GIT_ERROR_INVALID, "invalid option key"); error = -1; } va_end(ap); return error; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/message.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "message.h" static size_t line_length_without_trailing_spaces(const char *line, size_t len) { while (len) { unsigned char c = line[len - 1]; if (!git__isspace(c)) break; len--; } return len; } /* Greatly inspired from git.git "stripspace" */ /* see https://github.com/git/git/blob/497215d8811ac7b8955693ceaad0899ecd894ed2/builtin/stripspace.c#L4-67 */ int git_message_prettify(git_buf *message_out, const char *message, int strip_comments, char comment_char) { const size_t message_len = strlen(message); int consecutive_empty_lines = 0; size_t i, line_length, rtrimmed_line_length; char *next_newline; int error; if ((error = git_buf_sanitize(message_out)) < 0) return error; for (i = 0; i < strlen(message); i += line_length) { next_newline = memchr(message + i, '\n', message_len - i); if (next_newline != NULL) { line_length = next_newline - (message + i) + 1; } else { line_length = message_len - i; } if (strip_comments && line_length && message[i] == comment_char) continue; rtrimmed_line_length = line_length_without_trailing_spaces(message + i, line_length); if (!rtrimmed_line_length) { consecutive_empty_lines++; continue; } if (consecutive_empty_lines > 0 && message_out->size > 0) git_buf_putc(message_out, '\n'); consecutive_empty_lines = 0; git_buf_put(message_out, message + i, rtrimmed_line_length); git_buf_putc(message_out, '\n'); } return git_buf_oom(message_out) ? -1 : 0; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/object_api.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "common.h" #include "git2/object.h" #include "repository.h" #include "commit.h" #include "tree.h" #include "blob.h" #include "tag.h" /** * Commit */ int git_commit_lookup(git_commit **out, git_repository *repo, const git_oid *id) { return git_object_lookup((git_object **)out, repo, id, GIT_OBJECT_COMMIT); } int git_commit_lookup_prefix(git_commit **out, git_repository *repo, const git_oid *id, size_t len) { return git_object_lookup_prefix((git_object **)out, repo, id, len, GIT_OBJECT_COMMIT); } void git_commit_free(git_commit *obj) { git_object_free((git_object *)obj); } const git_oid *git_commit_id(const git_commit *obj) { return git_object_id((const git_object *)obj); } git_repository *git_commit_owner(const git_commit *obj) { return git_object_owner((const git_object *)obj); } int git_commit_dup(git_commit **out, git_commit *obj) { return git_object_dup((git_object **)out, (git_object *)obj); } /** * Tree */ int git_tree_lookup(git_tree **out, git_repository *repo, const git_oid *id) { return git_object_lookup((git_object **)out, repo, id, GIT_OBJECT_TREE); } int git_tree_lookup_prefix(git_tree **out, git_repository *repo, const git_oid *id, size_t len) { return git_object_lookup_prefix((git_object **)out, repo, id, len, GIT_OBJECT_TREE); } void git_tree_free(git_tree *obj) { git_object_free((git_object *)obj); } const git_oid *git_tree_id(const git_tree *obj) { return git_object_id((const git_object *)obj); } git_repository *git_tree_owner(const git_tree *obj) { return git_object_owner((const git_object *)obj); } int git_tree_dup(git_tree **out, git_tree *obj) { return git_object_dup((git_object **)out, (git_object *)obj); } /** * Tag */ int git_tag_lookup(git_tag **out, git_repository *repo, const git_oid *id) { return git_object_lookup((git_object **)out, repo, id, GIT_OBJECT_TAG); } int git_tag_lookup_prefix(git_tag **out, git_repository *repo, const git_oid *id, size_t len) { return git_object_lookup_prefix((git_object **)out, repo, id, len, GIT_OBJECT_TAG); } void git_tag_free(git_tag *obj) { git_object_free((git_object *)obj); } const git_oid *git_tag_id(const git_tag *obj) { return git_object_id((const git_object *)obj); } git_repository *git_tag_owner(const git_tag *obj) { return git_object_owner((const git_object *)obj); } int git_tag_dup(git_tag **out, git_tag *obj) { return git_object_dup((git_object **)out, (git_object *)obj); } /** * Blob */ int git_blob_lookup(git_blob **out, git_repository *repo, const git_oid *id) { return git_object_lookup((git_object **)out, repo, id, GIT_OBJECT_BLOB); } int git_blob_lookup_prefix(git_blob **out, git_repository *repo, const git_oid *id, size_t len) { return git_object_lookup_prefix((git_object **)out, repo, id, len, GIT_OBJECT_BLOB); } void git_blob_free(git_blob *obj) { git_object_free((git_object *)obj); } const git_oid *git_blob_id(const git_blob *obj) { return git_object_id((const git_object *)obj); } git_repository *git_blob_owner(const git_blob *obj) { return git_object_owner((const git_object *)obj); } int git_blob_dup(git_blob **out, git_blob *obj) { return git_object_dup((git_object **)out, (git_object *)obj); }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/refdb_fs.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "refs.h" #include "hash.h" #include "repository.h" #include "futils.h" #include "filebuf.h" #include "pack.h" #include "parse.h" #include "reflog.h" #include "refdb.h" #include "iterator.h" #include "sortedcache.h" #include "signature.h" #include "wildmatch.h" #include <git2/tag.h> #include <git2/object.h> #include <git2/refdb.h> #include <git2/branch.h> #include <git2/sys/refdb_backend.h> #include <git2/sys/refs.h> #include <git2/sys/reflog.h> #define DEFAULT_NESTING_LEVEL 5 #define MAX_NESTING_LEVEL 10 enum { PACKREF_HAS_PEEL = 1, PACKREF_WAS_LOOSE = 2, PACKREF_CANNOT_PEEL = 4, PACKREF_SHADOWED = 8, }; enum { PEELING_NONE = 0, PEELING_STANDARD, PEELING_FULL }; struct packref { git_oid oid; git_oid peel; char flags; char name[GIT_FLEX_ARRAY]; }; typedef struct refdb_fs_backend { git_refdb_backend parent; git_repository *repo; /* path to git directory */ char *gitpath; /* path to common objects' directory */ char *commonpath; git_sortedcache *refcache; int peeling_mode; git_iterator_flag_t iterator_flags; uint32_t direach_flags; int fsync; } refdb_fs_backend; static int refdb_reflog_fs__delete(git_refdb_backend *_backend, const char *name); GIT_INLINE(int) loose_path( git_buf *out, const char *base, const char *refname) { if (git_buf_joinpath(out, base, refname) < 0) return -1; return git_path_validate_filesystem_with_suffix(out->ptr, out->size, CONST_STRLEN(".lock")); } GIT_INLINE(int) reflog_path( git_buf *out, git_repository *repo, const char *refname) { const char *base; int error; base = (strcmp(refname, GIT_HEAD_FILE) == 0) ? repo->gitdir : repo->commondir; if ((error = git_buf_joinpath(out, base, GIT_REFLOG_DIR)) < 0) return error; return loose_path(out, out->ptr, refname); } static int packref_cmp(const void *a_, const void *b_) { const struct packref *a = a_, *b = b_; return strcmp(a->name, b->name); } static int packed_reload(refdb_fs_backend *backend) { int error; git_buf packedrefs = GIT_BUF_INIT; char *scan, *eof, *eol; if (!backend->gitpath) return 0; error = git_sortedcache_lockandload(backend->refcache, &packedrefs); /* * If we can't find the packed-refs, clear table and return. * Any other error just gets passed through. * If no error, and file wasn't changed, just return. * Anything else means we need to refresh the packed refs. */ if (error <= 0) { if (error == GIT_ENOTFOUND) { GIT_UNUSED(git_sortedcache_clear(backend->refcache, true)); git_error_clear(); error = 0; } return error; } /* At this point, refresh the packed refs from the loaded buffer. */ GIT_UNUSED(git_sortedcache_clear(backend->refcache, false)); scan = (char *)packedrefs.ptr; eof = scan + packedrefs.size; backend->peeling_mode = PEELING_NONE; if (*scan == '#') { static const char *traits_header = "# pack-refs with: "; if (git__prefixcmp(scan, traits_header) == 0) { scan += strlen(traits_header); eol = strchr(scan, '\n'); if (!eol) goto parse_failed; *eol = '\0'; if (strstr(scan, " fully-peeled ") != NULL) { backend->peeling_mode = PEELING_FULL; } else if (strstr(scan, " peeled ") != NULL) { backend->peeling_mode = PEELING_STANDARD; } scan = eol + 1; } } while (scan < eof && *scan == '#') { if (!(eol = strchr(scan, '\n'))) goto parse_failed; scan = eol + 1; } while (scan < eof) { struct packref *ref; git_oid oid; /* parse "<OID> <refname>\n" */ if (git_oid_fromstr(&oid, scan) < 0) goto parse_failed; scan += GIT_OID_HEXSZ; if (*scan++ != ' ') goto parse_failed; if (!(eol = strchr(scan, '\n'))) goto parse_failed; *eol = '\0'; if (eol[-1] == '\r') eol[-1] = '\0'; if (git_sortedcache_upsert((void **)&ref, backend->refcache, scan) < 0) goto parse_failed; scan = eol + 1; git_oid_cpy(&ref->oid, &oid); /* look for optional "^<OID>\n" */ if (*scan == '^') { if (git_oid_fromstr(&oid, scan + 1) < 0) goto parse_failed; scan += GIT_OID_HEXSZ + 1; if (scan < eof) { if (!(eol = strchr(scan, '\n'))) goto parse_failed; scan = eol + 1; } git_oid_cpy(&ref->peel, &oid); ref->flags |= PACKREF_HAS_PEEL; } else if (backend->peeling_mode == PEELING_FULL || (backend->peeling_mode == PEELING_STANDARD && git__prefixcmp(ref->name, GIT_REFS_TAGS_DIR) == 0)) ref->flags |= PACKREF_CANNOT_PEEL; } git_sortedcache_wunlock(backend->refcache); git_buf_dispose(&packedrefs); return 0; parse_failed: git_error_set(GIT_ERROR_REFERENCE, "corrupted packed references file"); GIT_UNUSED(git_sortedcache_clear(backend->refcache, false)); git_sortedcache_wunlock(backend->refcache); git_buf_dispose(&packedrefs); return -1; } static int loose_parse_oid( git_oid *oid, const char *filename, git_buf *file_content) { const char *str = git_buf_cstr(file_content); if (git_buf_len(file_content) < GIT_OID_HEXSZ) goto corrupted; /* we need to get 40 OID characters from the file */ if (git_oid_fromstr(oid, str) < 0) goto corrupted; /* If the file is longer than 40 chars, the 41st must be a space */ str += GIT_OID_HEXSZ; if (*str == '\0' || git__isspace(*str)) return 0; corrupted: git_error_set(GIT_ERROR_REFERENCE, "corrupted loose reference file: %s", filename); return -1; } static int loose_readbuffer(git_buf *buf, const char *base, const char *path) { int error; if ((error = loose_path(buf, base, path)) < 0 || (error = git_futils_readbuffer(buf, buf->ptr)) < 0) git_buf_dispose(buf); return error; } static int loose_lookup_to_packfile(refdb_fs_backend *backend, const char *name) { int error = 0; git_buf ref_file = GIT_BUF_INIT; struct packref *ref = NULL; git_oid oid; /* if we fail to load the loose reference, assume someone changed * the filesystem under us and skip it... */ if (loose_readbuffer(&ref_file, backend->gitpath, name) < 0) { git_error_clear(); goto done; } /* skip symbolic refs */ if (!git__prefixcmp(git_buf_cstr(&ref_file), GIT_SYMREF)) goto done; /* parse OID from file */ if ((error = loose_parse_oid(&oid, name, &ref_file)) < 0) goto done; if ((error = git_sortedcache_wlock(backend->refcache)) < 0) goto done; if (!(error = git_sortedcache_upsert( (void **)&ref, backend->refcache, name))) { git_oid_cpy(&ref->oid, &oid); ref->flags = PACKREF_WAS_LOOSE; } git_sortedcache_wunlock(backend->refcache); done: git_buf_dispose(&ref_file); return error; } static int _dirent_loose_load(void *payload, git_buf *full_path) { refdb_fs_backend *backend = payload; const char *file_path; if (git__suffixcmp(full_path->ptr, ".lock") == 0) return 0; if (git_path_isdir(full_path->ptr)) { int error = git_path_direach( full_path, backend->direach_flags, _dirent_loose_load, backend); /* Race with the filesystem, ignore it */ if (error == GIT_ENOTFOUND) { git_error_clear(); return 0; } return error; } file_path = full_path->ptr + strlen(backend->gitpath); return loose_lookup_to_packfile(backend, file_path); } /* * Load all the loose references from the repository * into the in-memory Packfile, and build a vector with * all the references so it can be written back to * disk. */ static int packed_loadloose(refdb_fs_backend *backend) { int error; git_buf refs_path = GIT_BUF_INIT; if (git_buf_joinpath(&refs_path, backend->gitpath, GIT_REFS_DIR) < 0) return -1; /* * Load all the loose files from disk into the Packfile table. * This will overwrite any old packed entries with their * updated loose versions */ error = git_path_direach( &refs_path, backend->direach_flags, _dirent_loose_load, backend); git_buf_dispose(&refs_path); return error; } static int refdb_fs_backend__exists( int *exists, git_refdb_backend *_backend, const char *ref_name) { refdb_fs_backend *backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent); git_buf ref_path = GIT_BUF_INIT; int error; GIT_ASSERT_ARG(backend); *exists = 0; if ((error = loose_path(&ref_path, backend->gitpath, ref_name)) < 0) goto out; if (git_path_isfile(ref_path.ptr)) { *exists = 1; goto out; } if ((error = packed_reload(backend)) < 0) goto out; if (git_sortedcache_lookup(backend->refcache, ref_name) != NULL) { *exists = 1; goto out; } out: git_buf_dispose(&ref_path); return error; } static const char *loose_parse_symbolic(git_buf *file_content) { const unsigned int header_len = (unsigned int)strlen(GIT_SYMREF); const char *refname_start; refname_start = (const char *)file_content->ptr; if (git_buf_len(file_content) < header_len + 1) { git_error_set(GIT_ERROR_REFERENCE, "corrupted loose reference file"); return NULL; } /* * Assume we have already checked for the header * before calling this function */ refname_start += header_len; return refname_start; } /* * Returns whether a reference is stored per worktree or not. * Per-worktree references are: * * - all pseudorefs, e.g. HEAD and MERGE_HEAD * - all references stored inside of "refs/bisect/" */ static bool is_per_worktree_ref(const char *ref_name) { return git__prefixcmp(ref_name, "refs/") != 0 || git__prefixcmp(ref_name, "refs/bisect/") == 0; } static int loose_lookup( git_reference **out, refdb_fs_backend *backend, const char *ref_name) { git_buf ref_file = GIT_BUF_INIT; int error = 0; const char *ref_dir; if (out) *out = NULL; if (is_per_worktree_ref(ref_name)) ref_dir = backend->gitpath; else ref_dir = backend->commonpath; if ((error = loose_readbuffer(&ref_file, ref_dir, ref_name)) < 0) /* cannot read loose ref file - gah */; else if (git__prefixcmp(git_buf_cstr(&ref_file), GIT_SYMREF) == 0) { const char *target; git_buf_rtrim(&ref_file); if (!(target = loose_parse_symbolic(&ref_file))) error = -1; else if (out != NULL) *out = git_reference__alloc_symbolic(ref_name, target); } else { git_oid oid; if (!(error = loose_parse_oid(&oid, ref_name, &ref_file)) && out != NULL) *out = git_reference__alloc(ref_name, &oid, NULL); } git_buf_dispose(&ref_file); return error; } static int ref_error_notfound(const char *name) { git_error_set(GIT_ERROR_REFERENCE, "reference '%s' not found", name); return GIT_ENOTFOUND; } static int packed_lookup( git_reference **out, refdb_fs_backend *backend, const char *ref_name) { int error = 0; struct packref *entry; if ((error = packed_reload(backend)) < 0) return error; if (git_sortedcache_rlock(backend->refcache) < 0) return -1; entry = git_sortedcache_lookup(backend->refcache, ref_name); if (!entry) { error = ref_error_notfound(ref_name); } else { *out = git_reference__alloc(ref_name, &entry->oid, &entry->peel); if (!*out) error = -1; } git_sortedcache_runlock(backend->refcache); return error; } static int refdb_fs_backend__lookup( git_reference **out, git_refdb_backend *_backend, const char *ref_name) { refdb_fs_backend *backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent); int error; GIT_ASSERT_ARG(backend); if (!(error = loose_lookup(out, backend, ref_name))) return 0; /* only try to lookup this reference on the packfile if it * wasn't found on the loose refs; not if there was a critical error */ if (error == GIT_ENOTFOUND) { git_error_clear(); error = packed_lookup(out, backend, ref_name); } return error; } typedef struct { git_reference_iterator parent; char *glob; git_pool pool; git_vector loose; git_sortedcache *cache; size_t loose_pos; size_t packed_pos; } refdb_fs_iter; static void refdb_fs_backend__iterator_free(git_reference_iterator *_iter) { refdb_fs_iter *iter = GIT_CONTAINER_OF(_iter, refdb_fs_iter, parent); git_vector_free(&iter->loose); git_pool_clear(&iter->pool); git_sortedcache_free(iter->cache); git__free(iter); } static int iter_load_loose_paths(refdb_fs_backend *backend, refdb_fs_iter *iter) { int error = 0; git_buf path = GIT_BUF_INIT; git_iterator *fsit = NULL; git_iterator_options fsit_opts = GIT_ITERATOR_OPTIONS_INIT; const git_index_entry *entry = NULL; const char *ref_prefix = GIT_REFS_DIR; size_t ref_prefix_len = strlen(ref_prefix); if (!backend->commonpath) /* do nothing if no commonpath for loose refs */ return 0; fsit_opts.flags = backend->iterator_flags; if (iter->glob) { const char *last_sep = NULL; const char *pos; for (pos = iter->glob; *pos; ++pos) { switch (*pos) { case '?': case '*': case '[': case '\\': break; case '/': last_sep = pos; /* FALLTHROUGH */ default: continue; } break; } if (last_sep) { ref_prefix = iter->glob; ref_prefix_len = (last_sep - ref_prefix) + 1; } } if ((error = git_buf_puts(&path, backend->commonpath)) < 0 || (error = git_buf_put(&path, ref_prefix, ref_prefix_len)) < 0) { git_buf_dispose(&path); return error; } if ((error = git_iterator_for_filesystem(&fsit, path.ptr, &fsit_opts)) < 0) { git_buf_dispose(&path); return (iter->glob && error == GIT_ENOTFOUND)? 0 : error; } error = git_buf_sets(&path, ref_prefix); while (!error && !git_iterator_advance(&entry, fsit)) { const char *ref_name; char *ref_dup; git_buf_truncate(&path, ref_prefix_len); git_buf_puts(&path, entry->path); ref_name = git_buf_cstr(&path); if (git__suffixcmp(ref_name, ".lock") == 0 || (iter->glob && wildmatch(iter->glob, ref_name, 0) != 0)) continue; ref_dup = git_pool_strdup(&iter->pool, ref_name); if (!ref_dup) error = -1; else error = git_vector_insert(&iter->loose, ref_dup); } git_iterator_free(fsit); git_buf_dispose(&path); return error; } static int refdb_fs_backend__iterator_next( git_reference **out, git_reference_iterator *_iter) { int error = GIT_ITEROVER; refdb_fs_iter *iter = GIT_CONTAINER_OF(_iter, refdb_fs_iter, parent); refdb_fs_backend *backend = GIT_CONTAINER_OF(iter->parent.db->backend, refdb_fs_backend, parent); struct packref *ref; while (iter->loose_pos < iter->loose.length) { const char *path = git_vector_get(&iter->loose, iter->loose_pos++); if (loose_lookup(out, backend, path) == 0) { ref = git_sortedcache_lookup(iter->cache, path); if (ref) ref->flags |= PACKREF_SHADOWED; return 0; } git_error_clear(); } error = GIT_ITEROVER; while (iter->packed_pos < git_sortedcache_entrycount(iter->cache)) { ref = git_sortedcache_entry(iter->cache, iter->packed_pos++); if (!ref) /* stop now if another thread deleted refs and we past end */ break; if (ref->flags & PACKREF_SHADOWED) continue; if (iter->glob && wildmatch(iter->glob, ref->name, 0) != 0) continue; *out = git_reference__alloc(ref->name, &ref->oid, &ref->peel); error = (*out != NULL) ? 0 : -1; break; } return error; } static int refdb_fs_backend__iterator_next_name( const char **out, git_reference_iterator *_iter) { int error = GIT_ITEROVER; refdb_fs_iter *iter = GIT_CONTAINER_OF(_iter, refdb_fs_iter, parent); refdb_fs_backend *backend = GIT_CONTAINER_OF(iter->parent.db->backend, refdb_fs_backend, parent); struct packref *ref; while (iter->loose_pos < iter->loose.length) { const char *path = git_vector_get(&iter->loose, iter->loose_pos++); struct packref *ref; if (loose_lookup(NULL, backend, path) == 0) { ref = git_sortedcache_lookup(iter->cache, path); if (ref) ref->flags |= PACKREF_SHADOWED; *out = path; return 0; } git_error_clear(); } error = GIT_ITEROVER; while (iter->packed_pos < git_sortedcache_entrycount(iter->cache)) { ref = git_sortedcache_entry(iter->cache, iter->packed_pos++); if (!ref) /* stop now if another thread deleted refs and we past end */ break; if (ref->flags & PACKREF_SHADOWED) continue; if (iter->glob && wildmatch(iter->glob, ref->name, 0) != 0) continue; *out = ref->name; error = 0; break; } return error; } static int refdb_fs_backend__iterator( git_reference_iterator **out, git_refdb_backend *_backend, const char *glob) { refdb_fs_backend *backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent); refdb_fs_iter *iter = NULL; int error; GIT_ASSERT_ARG(backend); iter = git__calloc(1, sizeof(refdb_fs_iter)); GIT_ERROR_CHECK_ALLOC(iter); if ((error = git_pool_init(&iter->pool, 1)) < 0) goto out; if ((error = git_vector_init(&iter->loose, 8, NULL)) < 0) goto out; if (glob != NULL && (iter->glob = git_pool_strdup(&iter->pool, glob)) == NULL) { error = GIT_ERROR_NOMEMORY; goto out; } if ((error = iter_load_loose_paths(backend, iter)) < 0) goto out; if ((error = packed_reload(backend)) < 0) goto out; if ((error = git_sortedcache_copy(&iter->cache, backend->refcache, 1, NULL, NULL)) < 0) goto out; iter->parent.next = refdb_fs_backend__iterator_next; iter->parent.next_name = refdb_fs_backend__iterator_next_name; iter->parent.free = refdb_fs_backend__iterator_free; *out = (git_reference_iterator *)iter; out: if (error) refdb_fs_backend__iterator_free((git_reference_iterator *)iter); return error; } static bool ref_is_available( const char *old_ref, const char *new_ref, const char *this_ref) { if (old_ref == NULL || strcmp(old_ref, this_ref)) { size_t reflen = strlen(this_ref); size_t newlen = strlen(new_ref); size_t cmplen = reflen < newlen ? reflen : newlen; const char *lead = reflen < newlen ? new_ref : this_ref; if (!strncmp(new_ref, this_ref, cmplen) && lead[cmplen] == '/') { return false; } } return true; } static int reference_path_available( refdb_fs_backend *backend, const char *new_ref, const char *old_ref, int force) { size_t i; int error; if ((error = packed_reload(backend)) < 0) return error; if (!force) { int exists; if ((error = refdb_fs_backend__exists( &exists, (git_refdb_backend *)backend, new_ref)) < 0) { return error; } if (exists) { git_error_set(GIT_ERROR_REFERENCE, "failed to write reference '%s': a reference with " "that name already exists.", new_ref); return GIT_EEXISTS; } } if ((error = git_sortedcache_rlock(backend->refcache)) < 0) return error; for (i = 0; i < git_sortedcache_entrycount(backend->refcache); ++i) { struct packref *ref = git_sortedcache_entry(backend->refcache, i); if (ref && !ref_is_available(old_ref, new_ref, ref->name)) { git_sortedcache_runlock(backend->refcache); git_error_set(GIT_ERROR_REFERENCE, "path to reference '%s' collides with existing one", new_ref); return -1; } } git_sortedcache_runlock(backend->refcache); return 0; } static int loose_lock(git_filebuf *file, refdb_fs_backend *backend, const char *name) { int error, filebuf_flags; git_buf ref_path = GIT_BUF_INIT; const char *basedir; GIT_ASSERT_ARG(file); GIT_ASSERT_ARG(backend); GIT_ASSERT_ARG(name); if (!git_path_validate(backend->repo, name, 0, GIT_PATH_REJECT_FILESYSTEM_DEFAULTS)) { git_error_set(GIT_ERROR_INVALID, "invalid reference name '%s'", name); return GIT_EINVALIDSPEC; } if (is_per_worktree_ref(name)) basedir = backend->gitpath; else basedir = backend->commonpath; /* Remove a possibly existing empty directory hierarchy * which name would collide with the reference name */ if ((error = git_futils_rmdir_r(name, basedir, GIT_RMDIR_SKIP_NONEMPTY)) < 0) return error; if ((error = loose_path(&ref_path, basedir, name)) < 0) return error; filebuf_flags = GIT_FILEBUF_CREATE_LEADING_DIRS; if (backend->fsync) filebuf_flags |= GIT_FILEBUF_FSYNC; error = git_filebuf_open(file, ref_path.ptr, filebuf_flags, GIT_REFS_FILE_MODE); if (error == GIT_EDIRECTORY) git_error_set(GIT_ERROR_REFERENCE, "cannot lock ref '%s', there are refs beneath that folder", name); git_buf_dispose(&ref_path); return error; } static int loose_commit(git_filebuf *file, const git_reference *ref) { GIT_ASSERT_ARG(file); GIT_ASSERT_ARG(ref); if (ref->type == GIT_REFERENCE_DIRECT) { char oid[GIT_OID_HEXSZ + 1]; git_oid_nfmt(oid, sizeof(oid), &ref->target.oid); git_filebuf_printf(file, "%s\n", oid); } else if (ref->type == GIT_REFERENCE_SYMBOLIC) { git_filebuf_printf(file, GIT_SYMREF "%s\n", ref->target.symbolic); } else { GIT_ASSERT(0); } return git_filebuf_commit(file); } static int refdb_fs_backend__lock(void **out, git_refdb_backend *_backend, const char *refname) { int error; git_filebuf *lock; refdb_fs_backend *backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent); lock = git__calloc(1, sizeof(git_filebuf)); GIT_ERROR_CHECK_ALLOC(lock); if ((error = loose_lock(lock, backend, refname)) < 0) { git__free(lock); return error; } *out = lock; return 0; } static int refdb_fs_backend__write_tail( git_refdb_backend *_backend, const git_reference *ref, git_filebuf *file, int update_reflog, const git_oid *old_id, const char *old_target, const git_signature *who, const char *message); static int refdb_fs_backend__delete_tail( git_refdb_backend *_backend, git_filebuf *file, const char *ref_name, const git_oid *old_id, const char *old_target); static int refdb_fs_backend__unlock(git_refdb_backend *backend, void *payload, int success, int update_reflog, const git_reference *ref, const git_signature *sig, const char *message) { git_filebuf *lock = (git_filebuf *) payload; int error = 0; if (success == 2) error = refdb_fs_backend__delete_tail(backend, lock, ref->name, NULL, NULL); else if (success) error = refdb_fs_backend__write_tail(backend, ref, lock, update_reflog, NULL, NULL, sig, message); else git_filebuf_cleanup(lock); git__free(lock); return error; } /* * Find out what object this reference resolves to. * * For references that point to a 'big' tag (e.g. an * actual tag object on the repository), we need to * cache on the packfile the OID of the object to * which that 'big tag' is pointing to. */ static int packed_find_peel(refdb_fs_backend *backend, struct packref *ref) { git_object *object; if (ref->flags & PACKREF_HAS_PEEL || ref->flags & PACKREF_CANNOT_PEEL) return 0; /* * Find the tagged object in the repository */ if (git_object_lookup(&object, backend->repo, &ref->oid, GIT_OBJECT_ANY) < 0) return -1; /* * If the tagged object is a Tag object, we need to resolve it; * if the ref is actually a 'weak' ref, we don't need to resolve * anything. */ if (git_object_type(object) == GIT_OBJECT_TAG) { git_tag *tag = (git_tag *)object; /* * Find the object pointed at by this tag */ git_oid_cpy(&ref->peel, git_tag_target_id(tag)); ref->flags |= PACKREF_HAS_PEEL; /* * The reference has now cached the resolved OID, and is * marked at such. When written to the packfile, it'll be * accompanied by this resolved oid */ } git_object_free(object); return 0; } /* * Write a single reference into a packfile */ static int packed_write_ref(struct packref *ref, git_filebuf *file) { char oid[GIT_OID_HEXSZ + 1]; git_oid_nfmt(oid, sizeof(oid), &ref->oid); /* * For references that peel to an object in the repo, we must * write the resulting peel on a separate line, e.g. * * 6fa8a902cc1d18527e1355773c86721945475d37 refs/tags/libgit2-0.4 * ^2ec0cb7959b0bf965d54f95453f5b4b34e8d3100 * * This obviously only applies to tags. * The required peels have already been loaded into `ref->peel_target`. */ if (ref->flags & PACKREF_HAS_PEEL) { char peel[GIT_OID_HEXSZ + 1]; git_oid_nfmt(peel, sizeof(peel), &ref->peel); if (git_filebuf_printf(file, "%s %s\n^%s\n", oid, ref->name, peel) < 0) return -1; } else { if (git_filebuf_printf(file, "%s %s\n", oid, ref->name) < 0) return -1; } return 0; } /* * Remove all loose references * * Once we have successfully written a packfile, * all the loose references that were packed must be * removed from disk. * * This is a dangerous method; make sure the packfile * is well-written, because we are destructing references * here otherwise. */ static int packed_remove_loose(refdb_fs_backend *backend) { size_t i; git_filebuf lock = GIT_FILEBUF_INIT; git_buf ref_content = GIT_BUF_INIT; int error = 0; /* backend->refcache is already locked when this is called */ for (i = 0; i < git_sortedcache_entrycount(backend->refcache); ++i) { struct packref *ref = git_sortedcache_entry(backend->refcache, i); git_oid current_id; if (!ref || !(ref->flags & PACKREF_WAS_LOOSE)) continue; git_filebuf_cleanup(&lock); /* We need to stop anybody from updating the ref while we try to do a safe delete */ error = loose_lock(&lock, backend, ref->name); /* If someone else is updating it, let them do it */ if (error == GIT_EEXISTS || error == GIT_ENOTFOUND) continue; if (error < 0) { git_buf_dispose(&ref_content); git_error_set(GIT_ERROR_REFERENCE, "failed to lock loose reference '%s'", ref->name); return error; } error = git_futils_readbuffer(&ref_content, lock.path_original); /* Someone else beat us to cleaning up the ref, let's simply continue */ if (error == GIT_ENOTFOUND) continue; /* This became a symref between us packing and trying to delete it, so ignore it */ if (!git__prefixcmp(ref_content.ptr, GIT_SYMREF)) continue; /* Figure out the current id; if we find a bad ref file, skip it so we can do the rest */ if (loose_parse_oid(&current_id, lock.path_original, &ref_content) < 0) continue; /* If the ref moved since we packed it, we must not delete it */ if (!git_oid_equal(&current_id, &ref->oid)) continue; /* * if we fail to remove a single file, this is *not* good, * but we should keep going and remove as many as possible. * If we fail to remove, the ref is still in the old state, so * we haven't lost information. */ p_unlink(lock.path_original); } git_buf_dispose(&ref_content); git_filebuf_cleanup(&lock); return 0; } /* * Write all the contents in the in-memory packfile to disk. */ static int packed_write(refdb_fs_backend *backend) { git_sortedcache *refcache = backend->refcache; git_filebuf pack_file = GIT_FILEBUF_INIT; int error, open_flags = 0; size_t i; /* lock the cache to updates while we do this */ if ((error = git_sortedcache_wlock(refcache)) < 0) return error; if (backend->fsync) open_flags = GIT_FILEBUF_FSYNC; /* Open the file! */ if ((error = git_filebuf_open(&pack_file, git_sortedcache_path(refcache), open_flags, GIT_PACKEDREFS_FILE_MODE)) < 0) goto fail; /* Packfiles have a header... apparently * This is in fact not required, but we might as well print it * just for kicks */ if ((error = git_filebuf_printf(&pack_file, "%s\n", GIT_PACKEDREFS_HEADER)) < 0) goto fail; for (i = 0; i < git_sortedcache_entrycount(refcache); ++i) { struct packref *ref = git_sortedcache_entry(refcache, i); GIT_ASSERT(ref); if ((error = packed_find_peel(backend, ref)) < 0) goto fail; if ((error = packed_write_ref(ref, &pack_file)) < 0) goto fail; } /* if we've written all the references properly, we can commit * the packfile to make the changes effective */ if ((error = git_filebuf_commit(&pack_file)) < 0) goto fail; /* when and only when the packfile has been properly written, * we can go ahead and remove the loose refs */ if ((error = packed_remove_loose(backend)) < 0) goto fail; git_sortedcache_updated(refcache); git_sortedcache_wunlock(refcache); /* we're good now */ return 0; fail: git_filebuf_cleanup(&pack_file); git_sortedcache_wunlock(refcache); return error; } static int packed_delete(refdb_fs_backend *backend, const char *ref_name) { size_t pack_pos; int error, found = 0; if ((error = packed_reload(backend)) < 0) goto cleanup; if ((error = git_sortedcache_wlock(backend->refcache)) < 0) goto cleanup; /* If a packed reference exists, remove it from the packfile and repack if necessary */ error = git_sortedcache_lookup_index(&pack_pos, backend->refcache, ref_name); if (error == 0) { error = git_sortedcache_remove(backend->refcache, pack_pos); found = 1; } if (error == GIT_ENOTFOUND) error = 0; git_sortedcache_wunlock(backend->refcache); if (found) error = packed_write(backend); cleanup: return error; } static int reflog_append(refdb_fs_backend *backend, const git_reference *ref, const git_oid *old, const git_oid *new, const git_signature *author, const char *message); static int cmp_old_ref(int *cmp, git_refdb_backend *backend, const char *name, const git_oid *old_id, const char *old_target) { int error = 0; git_reference *old_ref = NULL; *cmp = 0; /* It "matches" if there is no old value to compare against */ if (!old_id && !old_target) return 0; if ((error = refdb_fs_backend__lookup(&old_ref, backend, name)) < 0) { if (error == GIT_ENOTFOUND && old_id && git_oid_is_zero(old_id)) return 0; goto out; } /* If the types don't match, there's no way the values do */ if (old_id && old_ref->type != GIT_REFERENCE_DIRECT) { *cmp = -1; goto out; } if (old_target && old_ref->type != GIT_REFERENCE_SYMBOLIC) { *cmp = 1; goto out; } if (old_id && old_ref->type == GIT_REFERENCE_DIRECT) *cmp = git_oid_cmp(old_id, &old_ref->target.oid); if (old_target && old_ref->type == GIT_REFERENCE_SYMBOLIC) *cmp = git__strcmp(old_target, old_ref->target.symbolic); out: git_reference_free(old_ref); return error; } /* * The git.git comment regarding this, for your viewing pleasure: * * Special hack: If a branch is updated directly and HEAD * points to it (may happen on the remote side of a push * for example) then logically the HEAD reflog should be * updated too. * A generic solution implies reverse symref information, * but finding all symrefs pointing to the given branch * would be rather costly for this rare event (the direct * update of a branch) to be worth it. So let's cheat and * check with HEAD only which should cover 99% of all usage * scenarios (even 100% of the default ones). */ static int maybe_append_head(refdb_fs_backend *backend, const git_reference *ref, const git_signature *who, const char *message) { git_reference *head = NULL; git_refdb *refdb = NULL; int error, write_reflog; git_oid old_id; if ((error = git_repository_refdb(&refdb, backend->repo)) < 0 || (error = git_refdb_should_write_head_reflog(&write_reflog, refdb, ref)) < 0) goto out; if (!write_reflog) goto out; /* if we can't resolve, we use {0}*40 as old id */ if (git_reference_name_to_id(&old_id, backend->repo, ref->name) < 0) memset(&old_id, 0, sizeof(old_id)); if ((error = git_reference_lookup(&head, backend->repo, GIT_HEAD_FILE)) < 0 || (error = reflog_append(backend, head, &old_id, git_reference_target(ref), who, message)) < 0) goto out; out: git_reference_free(head); git_refdb_free(refdb); return error; } static int refdb_fs_backend__write( git_refdb_backend *_backend, const git_reference *ref, int force, const git_signature *who, const char *message, const git_oid *old_id, const char *old_target) { refdb_fs_backend *backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent); git_filebuf file = GIT_FILEBUF_INIT; int error = 0; GIT_ASSERT_ARG(backend); if ((error = reference_path_available(backend, ref->name, NULL, force)) < 0) return error; /* We need to perform the reflog append and old value check under the ref's lock */ if ((error = loose_lock(&file, backend, ref->name)) < 0) return error; return refdb_fs_backend__write_tail(_backend, ref, &file, true, old_id, old_target, who, message); } static int refdb_fs_backend__write_tail( git_refdb_backend *_backend, const git_reference *ref, git_filebuf *file, int update_reflog, const git_oid *old_id, const char *old_target, const git_signature *who, const char *message) { refdb_fs_backend *backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent); int error = 0, cmp = 0, should_write; const char *new_target = NULL; const git_oid *new_id = NULL; if ((error = cmp_old_ref(&cmp, _backend, ref->name, old_id, old_target)) < 0) goto on_error; if (cmp) { git_error_set(GIT_ERROR_REFERENCE, "old reference value does not match"); error = GIT_EMODIFIED; goto on_error; } if (ref->type == GIT_REFERENCE_SYMBOLIC) new_target = ref->target.symbolic; else new_id = &ref->target.oid; error = cmp_old_ref(&cmp, _backend, ref->name, new_id, new_target); if (error < 0 && error != GIT_ENOTFOUND) goto on_error; /* Don't update if we have the same value */ if (!error && !cmp) { error = 0; goto on_error; /* not really error */ } if (update_reflog) { git_refdb *refdb; if ((error = git_repository_refdb__weakptr(&refdb, backend->repo)) < 0 || (error = git_refdb_should_write_reflog(&should_write, refdb, ref)) < 0) goto on_error; if (should_write) { if ((error = reflog_append(backend, ref, NULL, NULL, who, message)) < 0) goto on_error; if ((error = maybe_append_head(backend, ref, who, message)) < 0) goto on_error; } } return loose_commit(file, ref); on_error: git_filebuf_cleanup(file); return error; } static int refdb_fs_backend__prune_refs( refdb_fs_backend *backend, const char *ref_name, const char *prefix) { git_buf relative_path = GIT_BUF_INIT; git_buf base_path = GIT_BUF_INIT; size_t commonlen; int error; GIT_ASSERT_ARG(backend); GIT_ASSERT_ARG(ref_name); if ((error = git_buf_sets(&relative_path, ref_name)) < 0) goto cleanup; git_path_squash_slashes(&relative_path); if ((commonlen = git_path_common_dirlen("refs/heads/", git_buf_cstr(&relative_path))) == strlen("refs/heads/") || (commonlen = git_path_common_dirlen("refs/tags/", git_buf_cstr(&relative_path))) == strlen("refs/tags/") || (commonlen = git_path_common_dirlen("refs/remotes/", git_buf_cstr(&relative_path))) == strlen("refs/remotes/")) { git_buf_truncate(&relative_path, commonlen); if (prefix) error = git_buf_join3(&base_path, '/', backend->commonpath, prefix, git_buf_cstr(&relative_path)); else error = git_buf_joinpath(&base_path, backend->commonpath, git_buf_cstr(&relative_path)); if (!error) error = git_path_validate_filesystem(base_path.ptr, base_path.size); if (error < 0) goto cleanup; error = git_futils_rmdir_r(ref_name + commonlen, git_buf_cstr(&base_path), GIT_RMDIR_EMPTY_PARENTS | GIT_RMDIR_SKIP_ROOT); if (error == GIT_ENOTFOUND) error = 0; } cleanup: git_buf_dispose(&relative_path); git_buf_dispose(&base_path); return error; } static int refdb_fs_backend__delete( git_refdb_backend *_backend, const char *ref_name, const git_oid *old_id, const char *old_target) { refdb_fs_backend *backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent); git_filebuf file = GIT_FILEBUF_INIT; int error = 0; GIT_ASSERT_ARG(backend); GIT_ASSERT_ARG(ref_name); if ((error = loose_lock(&file, backend, ref_name)) < 0) return error; if ((error = refdb_reflog_fs__delete(_backend, ref_name)) < 0) { git_filebuf_cleanup(&file); return error; } return refdb_fs_backend__delete_tail(_backend, &file, ref_name, old_id, old_target); } static int loose_delete(refdb_fs_backend *backend, const char *ref_name) { git_buf path = GIT_BUF_INIT; int error = 0; if ((error = loose_path(&path, backend->commonpath, ref_name)) < 0) return error; error = p_unlink(path.ptr); if (error < 0 && errno == ENOENT) error = GIT_ENOTFOUND; else if (error != 0) error = -1; git_buf_dispose(&path); return error; } static int refdb_fs_backend__delete_tail( git_refdb_backend *_backend, git_filebuf *file, const char *ref_name, const git_oid *old_id, const char *old_target) { refdb_fs_backend *backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent); int error = 0, cmp = 0; bool packed_deleted = 0; error = cmp_old_ref(&cmp, _backend, ref_name, old_id, old_target); if (error < 0) goto cleanup; if (cmp) { git_error_set(GIT_ERROR_REFERENCE, "old reference value does not match"); error = GIT_EMODIFIED; goto cleanup; } /* * To ensure that an external observer will see either the current ref value * (because the loose ref still exists), or a missing ref (after the packed-file is * unlocked, there will be nothing left), we must ensure things happen in the * following order: * * - the packed-ref file is locked and loaded, as well as a loose one, if it exists * - we optimistically delete a packed ref, keeping track of whether it existed * - we delete the loose ref, note that we have its .lock * - the loose ref is "unlocked", then the packed-ref file is rewritten and unlocked * - we should prune the path components if a loose ref was deleted * * Note that, because our packed backend doesn't expose its filesystem lock, * we might not be able to guarantee that this is what actually happens (ie. * as our current code never write packed-refs.lock, nothing stops observers * from grabbing a "stale" value from there). */ if ((error = packed_delete(backend, ref_name)) < 0 && error != GIT_ENOTFOUND) goto cleanup; if (error == 0) packed_deleted = 1; if ((error = loose_delete(backend, ref_name)) < 0 && error != GIT_ENOTFOUND) goto cleanup; if (error == GIT_ENOTFOUND) { error = packed_deleted ? 0 : ref_error_notfound(ref_name); goto cleanup; } cleanup: git_filebuf_cleanup(file); if (error == 0) error = refdb_fs_backend__prune_refs(backend, ref_name, ""); return error; } static int refdb_reflog_fs__rename(git_refdb_backend *_backend, const char *old_name, const char *new_name); static int refdb_fs_backend__rename( git_reference **out, git_refdb_backend *_backend, const char *old_name, const char *new_name, int force, const git_signature *who, const char *message) { refdb_fs_backend *backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent); git_reference *old, *new = NULL; git_filebuf file = GIT_FILEBUF_INIT; int error; GIT_ASSERT_ARG(backend); if ((error = reference_path_available( backend, new_name, old_name, force)) < 0 || (error = refdb_fs_backend__lookup(&old, _backend, old_name)) < 0) return error; if ((error = refdb_fs_backend__delete(_backend, old_name, NULL, NULL)) < 0) { git_reference_free(old); return error; } new = git_reference__realloc(&old, new_name); if (!new) { git_reference_free(old); return -1; } if ((error = loose_lock(&file, backend, new->name)) < 0) { git_reference_free(new); return error; } /* Try to rename the refog; it's ok if the old doesn't exist */ error = refdb_reflog_fs__rename(_backend, old_name, new_name); if (((error == 0) || (error == GIT_ENOTFOUND)) && ((error = reflog_append(backend, new, git_reference_target(new), NULL, who, message)) < 0)) { git_reference_free(new); git_filebuf_cleanup(&file); return error; } if (error < 0) { git_reference_free(new); git_filebuf_cleanup(&file); return error; } if ((error = loose_commit(&file, new)) < 0 || out == NULL) { git_reference_free(new); return error; } *out = new; return 0; } static int refdb_fs_backend__compress(git_refdb_backend *_backend) { int error; refdb_fs_backend *backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent); GIT_ASSERT_ARG(backend); if ((error = packed_reload(backend)) < 0 || /* load the existing packfile */ (error = packed_loadloose(backend)) < 0 || /* add all the loose refs */ (error = packed_write(backend)) < 0) /* write back to disk */ return error; return 0; } static void refdb_fs_backend__free(git_refdb_backend *_backend) { refdb_fs_backend *backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent); if (!backend) return; git_sortedcache_free(backend->refcache); git__free(backend->gitpath); git__free(backend->commonpath); git__free(backend); } static char *setup_namespace(git_repository *repo, const char *in) { git_buf path = GIT_BUF_INIT; char *parts, *start, *end, *out = NULL; if (!in) goto done; git_buf_puts(&path, in); /* if the repo is not namespaced, nothing else to do */ if (repo->namespace == NULL) { out = git_buf_detach(&path); goto done; } parts = end = git__strdup(repo->namespace); if (parts == NULL) goto done; /* * From `man gitnamespaces`: * namespaces which include a / will expand to a hierarchy * of namespaces; for example, GIT_NAMESPACE=foo/bar will store * refs under refs/namespaces/foo/refs/namespaces/bar/ */ while ((start = git__strsep(&end, "/")) != NULL) git_buf_printf(&path, "refs/namespaces/%s/", start); git_buf_printf(&path, "refs/namespaces/%s/refs", end); git__free(parts); /* Make sure that the folder with the namespace exists */ if (git_futils_mkdir_relative(git_buf_cstr(&path), in, 0777, GIT_MKDIR_PATH, NULL) < 0) goto done; /* Return root of the namespaced gitpath, i.e. without the trailing 'refs' */ git_buf_rtruncate_at_char(&path, '/'); git_buf_putc(&path, '/'); out = git_buf_detach(&path); done: git_buf_dispose(&path); return out; } static int reflog_alloc(git_reflog **reflog, const char *name) { git_reflog *log; *reflog = NULL; log = git__calloc(1, sizeof(git_reflog)); GIT_ERROR_CHECK_ALLOC(log); log->ref_name = git__strdup(name); GIT_ERROR_CHECK_ALLOC(log->ref_name); if (git_vector_init(&log->entries, 0, NULL) < 0) { git__free(log->ref_name); git__free(log); return -1; } *reflog = log; return 0; } static int reflog_parse(git_reflog *log, const char *buf, size_t buf_size) { git_parse_ctx parser = GIT_PARSE_CTX_INIT; if ((git_parse_ctx_init(&parser, buf, buf_size)) < 0) return -1; for (; parser.remain_len; git_parse_advance_line(&parser)) { git_reflog_entry *entry; const char *sig; char c; entry = git__calloc(1, sizeof(*entry)); GIT_ERROR_CHECK_ALLOC(entry); entry->committer = git__calloc(1, sizeof(*entry->committer)); GIT_ERROR_CHECK_ALLOC(entry->committer); if (git_parse_advance_oid(&entry->oid_old, &parser) < 0 || git_parse_advance_expected(&parser, " ", 1) < 0 || git_parse_advance_oid(&entry->oid_cur, &parser) < 0) goto next; sig = parser.line; while (git_parse_peek(&c, &parser, 0) == 0 && c != '\t' && c != '\n') git_parse_advance_chars(&parser, 1); if (git_signature__parse(entry->committer, &sig, parser.line, NULL, 0) < 0) goto next; if (c == '\t') { size_t len; git_parse_advance_chars(&parser, 1); len = parser.line_len; if (parser.line[len - 1] == '\n') len--; entry->msg = git__strndup(parser.line, len); GIT_ERROR_CHECK_ALLOC(entry->msg); } if ((git_vector_insert(&log->entries, entry)) < 0) { git_reflog_entry__free(entry); return -1; } continue; next: git_reflog_entry__free(entry); } return 0; } static int create_new_reflog_file(const char *filepath) { int fd, error; if ((error = git_futils_mkpath2file(filepath, GIT_REFLOG_DIR_MODE)) < 0) return error; if ((fd = p_open(filepath, O_WRONLY | O_CREAT, GIT_REFLOG_FILE_MODE)) < 0) return -1; return p_close(fd); } static int refdb_reflog_fs__ensure_log(git_refdb_backend *_backend, const char *name) { refdb_fs_backend *backend; git_repository *repo; git_buf path = GIT_BUF_INIT; int error; GIT_ASSERT_ARG(_backend && name); backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent); repo = backend->repo; if ((error = reflog_path(&path, repo, name)) < 0) return error; error = create_new_reflog_file(git_buf_cstr(&path)); git_buf_dispose(&path); return error; } static int has_reflog(git_repository *repo, const char *name) { int ret = 0; git_buf path = GIT_BUF_INIT; if (reflog_path(&path, repo, name) < 0) goto cleanup; ret = git_path_isfile(git_buf_cstr(&path)); cleanup: git_buf_dispose(&path); return ret; } static int refdb_reflog_fs__has_log(git_refdb_backend *_backend, const char *name) { refdb_fs_backend *backend; GIT_ASSERT_ARG(_backend); GIT_ASSERT_ARG(name); backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent); return has_reflog(backend->repo, name); } static int refdb_reflog_fs__read(git_reflog **out, git_refdb_backend *_backend, const char *name) { int error = -1; git_buf log_path = GIT_BUF_INIT; git_buf log_file = GIT_BUF_INIT; git_reflog *log = NULL; git_repository *repo; refdb_fs_backend *backend; GIT_ASSERT_ARG(out); GIT_ASSERT_ARG(_backend); GIT_ASSERT_ARG(name); backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent); repo = backend->repo; if (reflog_alloc(&log, name) < 0) return -1; if (reflog_path(&log_path, repo, name) < 0) goto cleanup; error = git_futils_readbuffer(&log_file, git_buf_cstr(&log_path)); if (error < 0 && error != GIT_ENOTFOUND) goto cleanup; if ((error == GIT_ENOTFOUND) && ((error = create_new_reflog_file(git_buf_cstr(&log_path))) < 0)) goto cleanup; if ((error = reflog_parse(log, git_buf_cstr(&log_file), git_buf_len(&log_file))) < 0) goto cleanup; *out = log; goto success; cleanup: git_reflog_free(log); success: git_buf_dispose(&log_file); git_buf_dispose(&log_path); return error; } static int serialize_reflog_entry( git_buf *buf, const git_oid *oid_old, const git_oid *oid_new, const git_signature *committer, const char *msg) { char raw_old[GIT_OID_HEXSZ+1]; char raw_new[GIT_OID_HEXSZ+1]; git_oid_tostr(raw_old, GIT_OID_HEXSZ+1, oid_old); git_oid_tostr(raw_new, GIT_OID_HEXSZ+1, oid_new); git_buf_clear(buf); git_buf_puts(buf, raw_old); git_buf_putc(buf, ' '); git_buf_puts(buf, raw_new); git_signature__writebuf(buf, " ", committer); /* drop trailing LF */ git_buf_rtrim(buf); if (msg) { size_t i; git_buf_putc(buf, '\t'); git_buf_puts(buf, msg); for (i = 0; i < buf->size - 2; i++) if (buf->ptr[i] == '\n') buf->ptr[i] = ' '; git_buf_rtrim(buf); } git_buf_putc(buf, '\n'); return git_buf_oom(buf); } static int lock_reflog(git_filebuf *file, refdb_fs_backend *backend, const char *refname) { git_repository *repo; git_buf log_path = GIT_BUF_INIT; int error; repo = backend->repo; if (!git_path_validate(backend->repo, refname, 0, GIT_PATH_REJECT_FILESYSTEM_DEFAULTS)) { git_error_set(GIT_ERROR_INVALID, "invalid reference name '%s'", refname); return GIT_EINVALIDSPEC; } if (reflog_path(&log_path, repo, refname) < 0) return -1; if (!git_path_isfile(git_buf_cstr(&log_path))) { git_error_set(GIT_ERROR_INVALID, "log file for reference '%s' doesn't exist", refname); error = -1; goto cleanup; } error = git_filebuf_open(file, git_buf_cstr(&log_path), 0, GIT_REFLOG_FILE_MODE); cleanup: git_buf_dispose(&log_path); return error; } static int refdb_reflog_fs__write(git_refdb_backend *_backend, git_reflog *reflog) { int error = -1; unsigned int i; git_reflog_entry *entry; refdb_fs_backend *backend; git_buf log = GIT_BUF_INIT; git_filebuf fbuf = GIT_FILEBUF_INIT; GIT_ASSERT_ARG(_backend); GIT_ASSERT_ARG(reflog); backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent); if ((error = lock_reflog(&fbuf, backend, reflog->ref_name)) < 0) return -1; git_vector_foreach(&reflog->entries, i, entry) { if (serialize_reflog_entry(&log, &(entry->oid_old), &(entry->oid_cur), entry->committer, entry->msg) < 0) goto cleanup; if ((error = git_filebuf_write(&fbuf, log.ptr, log.size)) < 0) goto cleanup; } error = git_filebuf_commit(&fbuf); goto success; cleanup: git_filebuf_cleanup(&fbuf); success: git_buf_dispose(&log); return error; } /* Append to the reflog, must be called under reference lock */ static int reflog_append(refdb_fs_backend *backend, const git_reference *ref, const git_oid *old, const git_oid *new, const git_signature *who, const char *message) { int error, is_symbolic, open_flags; git_oid old_id = {{0}}, new_id = {{0}}; git_buf buf = GIT_BUF_INIT, path = GIT_BUF_INIT; git_repository *repo = backend->repo; is_symbolic = ref->type == GIT_REFERENCE_SYMBOLIC; /* "normal" symbolic updates do not write */ if (is_symbolic && strcmp(ref->name, GIT_HEAD_FILE) && !(old && new)) return 0; /* From here on is_symbolic also means that it's HEAD */ if (old) { git_oid_cpy(&old_id, old); } else { error = git_reference_name_to_id(&old_id, repo, ref->name); if (error < 0 && error != GIT_ENOTFOUND) return error; } if (new) { git_oid_cpy(&new_id, new); } else { if (!is_symbolic) { git_oid_cpy(&new_id, git_reference_target(ref)); } else { error = git_reference_name_to_id(&new_id, repo, git_reference_symbolic_target(ref)); if (error < 0 && error != GIT_ENOTFOUND) return error; /* detaching HEAD does not create an entry */ if (error == GIT_ENOTFOUND) return 0; git_error_clear(); } } if ((error = serialize_reflog_entry(&buf, &old_id, &new_id, who, message)) < 0) goto cleanup; if ((error = reflog_path(&path, repo, ref->name)) < 0) goto cleanup; if (((error = git_futils_mkpath2file(git_buf_cstr(&path), 0777)) < 0) && (error != GIT_EEXISTS)) { goto cleanup; } /* If the new branch matches part of the namespace of a previously deleted branch, * there maybe an obsolete/unused directory (or directory hierarchy) in the way. */ if (git_path_isdir(git_buf_cstr(&path))) { if ((error = git_futils_rmdir_r(git_buf_cstr(&path), NULL, GIT_RMDIR_SKIP_NONEMPTY)) < 0) { if (error == GIT_ENOTFOUND) error = 0; } else if (git_path_isdir(git_buf_cstr(&path))) { git_error_set(GIT_ERROR_REFERENCE, "cannot create reflog at '%s', there are reflogs beneath that folder", ref->name); error = GIT_EDIRECTORY; } if (error != 0) goto cleanup; } open_flags = O_WRONLY | O_CREAT | O_APPEND; if (backend->fsync) open_flags |= O_FSYNC; error = git_futils_writebuffer(&buf, git_buf_cstr(&path), open_flags, GIT_REFLOG_FILE_MODE); cleanup: git_buf_dispose(&buf); git_buf_dispose(&path); return error; } static int refdb_reflog_fs__rename(git_refdb_backend *_backend, const char *old_name, const char *new_name) { int error = 0, fd; git_buf old_path = GIT_BUF_INIT; git_buf new_path = GIT_BUF_INIT; git_buf temp_path = GIT_BUF_INIT; git_buf normalized = GIT_BUF_INIT; git_repository *repo; refdb_fs_backend *backend; GIT_ASSERT_ARG(_backend); GIT_ASSERT_ARG(old_name); GIT_ASSERT_ARG(new_name); backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent); repo = backend->repo; if ((error = git_reference__normalize_name( &normalized, new_name, GIT_REFERENCE_FORMAT_ALLOW_ONELEVEL)) < 0) return error; if (git_buf_joinpath(&temp_path, repo->gitdir, GIT_REFLOG_DIR) < 0) return -1; if ((error = loose_path(&old_path, git_buf_cstr(&temp_path), old_name)) < 0) return error; if ((error = loose_path(&new_path, git_buf_cstr(&temp_path), git_buf_cstr(&normalized))) < 0) return error; if (!git_path_exists(git_buf_cstr(&old_path))) { error = GIT_ENOTFOUND; goto cleanup; } /* * Move the reflog to a temporary place. This two-phase renaming is required * in order to cope with funny renaming use cases when one tries to move a reference * to a partially colliding namespace: * - a/b -> a/b/c * - a/b/c/d -> a/b/c */ if ((error = loose_path(&temp_path, git_buf_cstr(&temp_path), "temp_reflog")) < 0) return error; if ((fd = git_futils_mktmp(&temp_path, git_buf_cstr(&temp_path), GIT_REFLOG_FILE_MODE)) < 0) { error = -1; goto cleanup; } p_close(fd); if (p_rename(git_buf_cstr(&old_path), git_buf_cstr(&temp_path)) < 0) { git_error_set(GIT_ERROR_OS, "failed to rename reflog for %s", new_name); error = -1; goto cleanup; } if (git_path_isdir(git_buf_cstr(&new_path)) && (git_futils_rmdir_r(git_buf_cstr(&new_path), NULL, GIT_RMDIR_SKIP_NONEMPTY) < 0)) { error = -1; goto cleanup; } if (git_futils_mkpath2file(git_buf_cstr(&new_path), GIT_REFLOG_DIR_MODE) < 0) { error = -1; goto cleanup; } if (p_rename(git_buf_cstr(&temp_path), git_buf_cstr(&new_path)) < 0) { git_error_set(GIT_ERROR_OS, "failed to rename reflog for %s", new_name); error = -1; } cleanup: git_buf_dispose(&temp_path); git_buf_dispose(&old_path); git_buf_dispose(&new_path); git_buf_dispose(&normalized); return error; } static int refdb_reflog_fs__delete(git_refdb_backend *_backend, const char *name) { refdb_fs_backend *backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent); git_buf path = GIT_BUF_INIT; int error; GIT_ASSERT_ARG(_backend); GIT_ASSERT_ARG(name); if ((error = reflog_path(&path, backend->repo, name)) < 0) goto out; if (!git_path_exists(path.ptr)) goto out; if ((error = p_unlink(path.ptr)) < 0) goto out; error = refdb_fs_backend__prune_refs(backend, name, GIT_REFLOG_DIR); out: git_buf_dispose(&path); return error; } int git_refdb_backend_fs( git_refdb_backend **backend_out, git_repository *repository) { int t = 0; git_buf gitpath = GIT_BUF_INIT; refdb_fs_backend *backend; backend = git__calloc(1, sizeof(refdb_fs_backend)); GIT_ERROR_CHECK_ALLOC(backend); if (git_refdb_init_backend(&backend->parent, GIT_REFDB_BACKEND_VERSION) < 0) goto fail; backend->repo = repository; if (repository->gitdir) { backend->gitpath = setup_namespace(repository, repository->gitdir); if (backend->gitpath == NULL) goto fail; } if (repository->commondir) { backend->commonpath = setup_namespace(repository, repository->commondir); if (backend->commonpath == NULL) goto fail; } if (git_buf_joinpath(&gitpath, backend->commonpath, GIT_PACKEDREFS_FILE) < 0 || git_sortedcache_new( &backend->refcache, offsetof(struct packref, name), NULL, NULL, packref_cmp, git_buf_cstr(&gitpath)) < 0) goto fail; git_buf_dispose(&gitpath); if (!git_repository__configmap_lookup(&t, backend->repo, GIT_CONFIGMAP_IGNORECASE) && t) { backend->iterator_flags |= GIT_ITERATOR_IGNORE_CASE; backend->direach_flags |= GIT_PATH_DIR_IGNORE_CASE; } if (!git_repository__configmap_lookup(&t, backend->repo, GIT_CONFIGMAP_PRECOMPOSE) && t) { backend->iterator_flags |= GIT_ITERATOR_PRECOMPOSE_UNICODE; backend->direach_flags |= GIT_PATH_DIR_PRECOMPOSE_UNICODE; } if ((!git_repository__configmap_lookup(&t, backend->repo, GIT_CONFIGMAP_FSYNCOBJECTFILES) && t) || git_repository__fsync_gitdir) backend->fsync = 1; backend->iterator_flags |= GIT_ITERATOR_DESCEND_SYMLINKS; backend->parent.exists = &refdb_fs_backend__exists; backend->parent.lookup = &refdb_fs_backend__lookup; backend->parent.iterator = &refdb_fs_backend__iterator; backend->parent.write = &refdb_fs_backend__write; backend->parent.del = &refdb_fs_backend__delete; backend->parent.rename = &refdb_fs_backend__rename; backend->parent.compress = &refdb_fs_backend__compress; backend->parent.lock = &refdb_fs_backend__lock; backend->parent.unlock = &refdb_fs_backend__unlock; backend->parent.has_log = &refdb_reflog_fs__has_log; backend->parent.ensure_log = &refdb_reflog_fs__ensure_log; backend->parent.free = &refdb_fs_backend__free; backend->parent.reflog_read = &refdb_reflog_fs__read; backend->parent.reflog_write = &refdb_reflog_fs__write; backend->parent.reflog_rename = &refdb_reflog_fs__rename; backend->parent.reflog_delete = &refdb_reflog_fs__delete; *backend_out = (git_refdb_backend *)backend; return 0; fail: git_buf_dispose(&gitpath); git__free(backend->gitpath); git__free(backend->commonpath); git__free(backend); return -1; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/refs.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_refs_h__ #define INCLUDE_refs_h__ #include "common.h" #include "git2/oid.h" #include "git2/refs.h" #include "git2/refdb.h" #include "strmap.h" #include "buffer.h" #include "oid.h" extern bool git_reference__enable_symbolic_ref_target_validation; #define GIT_REFS_DIR "refs/" #define GIT_REFS_HEADS_DIR GIT_REFS_DIR "heads/" #define GIT_REFS_TAGS_DIR GIT_REFS_DIR "tags/" #define GIT_REFS_REMOTES_DIR GIT_REFS_DIR "remotes/" #define GIT_REFS_NOTES_DIR GIT_REFS_DIR "notes/" #define GIT_REFS_DIR_MODE 0777 #define GIT_REFS_FILE_MODE 0666 #define GIT_RENAMED_REF_FILE GIT_REFS_DIR "RENAMED-REF" #define GIT_SYMREF "ref: " #define GIT_PACKEDREFS_FILE "packed-refs" #define GIT_PACKEDREFS_HEADER "# pack-refs with: peeled fully-peeled sorted " #define GIT_PACKEDREFS_FILE_MODE 0666 #define GIT_HEAD_FILE "HEAD" #define GIT_ORIG_HEAD_FILE "ORIG_HEAD" #define GIT_FETCH_HEAD_FILE "FETCH_HEAD" #define GIT_MERGE_HEAD_FILE "MERGE_HEAD" #define GIT_REVERT_HEAD_FILE "REVERT_HEAD" #define GIT_CHERRYPICK_HEAD_FILE "CHERRY_PICK_HEAD" #define GIT_BISECT_LOG_FILE "BISECT_LOG" #define GIT_REBASE_MERGE_DIR "rebase-merge/" #define GIT_REBASE_MERGE_INTERACTIVE_FILE GIT_REBASE_MERGE_DIR "interactive" #define GIT_REBASE_APPLY_DIR "rebase-apply/" #define GIT_REBASE_APPLY_REBASING_FILE GIT_REBASE_APPLY_DIR "rebasing" #define GIT_REBASE_APPLY_APPLYING_FILE GIT_REBASE_APPLY_DIR "applying" #define GIT_SEQUENCER_DIR "sequencer/" #define GIT_SEQUENCER_HEAD_FILE GIT_SEQUENCER_DIR "head" #define GIT_SEQUENCER_OPTIONS_FILE GIT_SEQUENCER_DIR "options" #define GIT_SEQUENCER_TODO_FILE GIT_SEQUENCER_DIR "todo" #define GIT_STASH_FILE "stash" #define GIT_REFS_STASH_FILE GIT_REFS_DIR GIT_STASH_FILE #define GIT_REFERENCE_FORMAT__PRECOMPOSE_UNICODE (1u << 16) #define GIT_REFERENCE_FORMAT__VALIDATION_DISABLE (1u << 15) #define GIT_REFNAME_MAX 1024 typedef char git_refname_t[GIT_REFNAME_MAX]; struct git_reference { git_refdb *db; git_reference_t type; union { git_oid oid; char *symbolic; } target; git_oid peel; char name[GIT_FLEX_ARRAY]; }; /** * Reallocate the reference with a new name * * Note that this is a dangerous operation, as on success, all existing * pointers to the old reference will now be dangling. Only call this on objects * you control, possibly using `git_reference_dup`. */ git_reference *git_reference__realloc(git_reference **ptr_to_ref, const char *name); int git_reference__normalize_name(git_buf *buf, const char *name, unsigned int flags); int git_reference__update_terminal(git_repository *repo, const char *ref_name, const git_oid *oid, const git_signature *sig, const char *log_message); int git_reference__name_is_valid(int *valid, const char *name, unsigned int flags); int git_reference__is_branch(const char *ref_name); int git_reference__is_remote(const char *ref_name); int git_reference__is_tag(const char *ref_name); int git_reference__is_note(const char *ref_name); const char *git_reference__shorthand(const char *name); /** * Lookup a reference by name and try to resolve to an OID. * * You can control how many dereferences this will attempt to resolve the * reference with the `max_deref` parameter, or pass -1 to use a sane * default. If you pass 0 for `max_deref`, this will not attempt to resolve * the reference. For any value of `max_deref` other than 0, not * successfully resolving the reference will be reported as an error. * The generated reference must be freed by the user. * * @param reference_out Pointer to the looked-up reference * @param repo The repository to look up the reference * @param name The long name for the reference (e.g. HEAD, ref/heads/master, refs/tags/v0.1.0, ...) * @param max_deref Maximum number of dereferences to make of symbolic refs, 0 means simple lookup, < 0 means use default reasonable value * @return 0 on success or < 0 on error; not being able to resolve the reference is an error unless 0 was passed for max_deref */ int git_reference_lookup_resolved( git_reference **reference_out, git_repository *repo, const char *name, int max_deref); int git_reference__log_signature(git_signature **out, git_repository *repo); /** Update a reference after a commit. */ int git_reference__update_for_commit( git_repository *repo, git_reference *ref, const char *ref_name, const git_oid *id, const char *operation); int git_reference__is_unborn_head(bool *unborn, const git_reference *ref, git_repository *repo); #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/patch.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_patch_h__ #define INCLUDE_patch_h__ #include "common.h" #include "git2/patch.h" #include "array.h" /* cached information about a hunk in a patch */ typedef struct git_patch_hunk { git_diff_hunk hunk; size_t line_start; size_t line_count; } git_patch_hunk; struct git_patch { git_refcount rc; git_repository *repo; /* may be null */ git_diff_options diff_opts; git_diff_delta *delta; git_diff_binary binary; git_array_t(git_patch_hunk) hunks; git_array_t(git_diff_line) lines; size_t header_size; size_t content_size; size_t context_size; void (*free_fn)(git_patch *patch); }; extern int git_patch__invoke_callbacks( git_patch *patch, git_diff_file_cb file_cb, git_diff_binary_cb binary_cb, git_diff_hunk_cb hunk_cb, git_diff_line_cb line_cb, void *payload); extern int git_patch_line_stats( size_t *total_ctxt, size_t *total_adds, size_t *total_dels, const git_patch *patch); /** Options for parsing patch files. */ typedef struct { /** * The length of the prefix (in path segments) for the filenames. * This prefix will be removed when looking for files. The default is 1. */ uint32_t prefix_len; } git_patch_options; #define GIT_PATCH_OPTIONS_INIT { 1 } extern void git_patch_free(git_patch *patch); #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/transaction.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_transaction_h__ #define INCLUDE_transaction_h__ #include "common.h" int git_transaction_config_new(git_transaction **out, git_config *cfg); #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/refspec.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_refspec_h__ #define INCLUDE_refspec_h__ #include "common.h" #include "git2/refspec.h" #include "buffer.h" #include "vector.h" struct git_refspec { char *string; char *src; char *dst; unsigned int force :1, push : 1, pattern :1, matching :1; }; #define GIT_REFSPEC_TAGS "refs/tags/*:refs/tags/*" int git_refspec__parse( struct git_refspec *refspec, const char *str, bool is_fetch); void git_refspec__dispose(git_refspec *refspec); int git_refspec__serialize(git_buf *out, const git_refspec *refspec); /** * Determines if a refspec is a wildcard refspec. * * @param spec the refspec * @return 1 if the refspec is a wildcard, 0 otherwise */ int git_refspec_is_wildcard(const git_refspec *spec); /** * DWIM `spec` with `refs` existing on the remote, append the dwim'ed * result in `out`. */ int git_refspec__dwim_one(git_vector *out, git_refspec *spec, git_vector *refs); #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/posix.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "posix.h" #include "path.h" #include <stdio.h> #include <ctype.h> size_t p_fsync__cnt = 0; #ifndef GIT_WIN32 #ifdef NO_ADDRINFO int p_getaddrinfo( const char *host, const char *port, struct addrinfo *hints, struct addrinfo **info) { struct addrinfo *ainfo, *ai; int p = 0; GIT_UNUSED(hints); if ((ainfo = git__malloc(sizeof(struct addrinfo))) == NULL) return -1; if ((ainfo->ai_hostent = gethostbyname(host)) == NULL) { git__free(ainfo); return -2; } ainfo->ai_servent = getservbyname(port, 0); if (ainfo->ai_servent) ainfo->ai_port = ainfo->ai_servent->s_port; else ainfo->ai_port = htons(atol(port)); memcpy(&ainfo->ai_addr_in.sin_addr, ainfo->ai_hostent->h_addr_list[0], ainfo->ai_hostent->h_length); ainfo->ai_protocol = 0; ainfo->ai_socktype = hints->ai_socktype; ainfo->ai_family = ainfo->ai_hostent->h_addrtype; ainfo->ai_addr_in.sin_family = ainfo->ai_family; ainfo->ai_addr_in.sin_port = ainfo->ai_port; ainfo->ai_addr = (struct addrinfo *)&ainfo->ai_addr_in; ainfo->ai_addrlen = sizeof(struct sockaddr_in); *info = ainfo; if (ainfo->ai_hostent->h_addr_list[1] == NULL) { ainfo->ai_next = NULL; return 0; } ai = ainfo; for (p = 1; ainfo->ai_hostent->h_addr_list[p] != NULL; p++) { if (!(ai->ai_next = git__malloc(sizeof(struct addrinfo)))) { p_freeaddrinfo(ainfo); return -1; } memcpy(ai->ai_next, ainfo, sizeof(struct addrinfo)); memcpy(&ai->ai_next->ai_addr_in.sin_addr, ainfo->ai_hostent->h_addr_list[p], ainfo->ai_hostent->h_length); ai->ai_next->ai_addr = (struct addrinfo *)&ai->ai_next->ai_addr_in; ai = ai->ai_next; } ai->ai_next = NULL; return 0; } void p_freeaddrinfo(struct addrinfo *info) { struct addrinfo *p, *next; p = info; while(p != NULL) { next = p->ai_next; git__free(p); p = next; } } const char *p_gai_strerror(int ret) { switch(ret) { case -1: return "Out of memory"; break; case -2: return "Address lookup failed"; break; default: return "Unknown error"; break; } } #endif /* NO_ADDRINFO */ int p_open(const char *path, volatile int flags, ...) { mode_t mode = 0; #ifdef GIT_DEBUG_STRICT_OPEN if (strstr(path, "//") != NULL) { errno = EACCES; return -1; } #endif if (flags & O_CREAT) { va_list arg_list; va_start(arg_list, flags); mode = (mode_t)va_arg(arg_list, int); va_end(arg_list); } return open(path, flags | O_BINARY | O_CLOEXEC, mode); } int p_creat(const char *path, mode_t mode) { return open(path, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_CLOEXEC, mode); } int p_getcwd(char *buffer_out, size_t size) { char *cwd_buffer; GIT_ASSERT_ARG(buffer_out); GIT_ASSERT_ARG(size > 0); cwd_buffer = getcwd(buffer_out, size); if (cwd_buffer == NULL) return -1; git_path_mkposix(buffer_out); git_path_string_to_dir(buffer_out, size); /* append trailing slash */ return 0; } int p_rename(const char *from, const char *to) { if (!link(from, to)) { p_unlink(from); return 0; } if (!rename(from, to)) return 0; return -1; } #endif /* GIT_WIN32 */ ssize_t p_read(git_file fd, void *buf, size_t cnt) { char *b = buf; if (!git__is_ssizet(cnt)) { #ifdef GIT_WIN32 SetLastError(ERROR_INVALID_PARAMETER); #endif errno = EINVAL; return -1; } while (cnt) { ssize_t r; #ifdef GIT_WIN32 r = read(fd, b, cnt > INT_MAX ? INT_MAX : (unsigned int)cnt); #else r = read(fd, b, cnt); #endif if (r < 0) { if (errno == EINTR || errno == EAGAIN) continue; return -1; } if (!r) break; cnt -= r; b += r; } return (b - (char *)buf); } int p_write(git_file fd, const void *buf, size_t cnt) { const char *b = buf; while (cnt) { ssize_t r; #ifdef GIT_WIN32 GIT_ASSERT((size_t)((unsigned int)cnt) == cnt); r = write(fd, b, (unsigned int)cnt); #else r = write(fd, b, cnt); #endif if (r < 0) { if (errno == EINTR || GIT_ISBLOCKED(errno)) continue; return -1; } if (!r) { errno = EPIPE; return -1; } cnt -= r; b += r; } return 0; } #ifdef NO_MMAP #include "map.h" int git__page_size(size_t *page_size) { /* dummy; here we don't need any alignment anyway */ *page_size = 4096; return 0; } int git__mmap_alignment(size_t *alignment) { /* dummy; here we don't need any alignment anyway */ *alignment = 4096; return 0; } int p_mmap(git_map *out, size_t len, int prot, int flags, int fd, off64_t offset) { const char *ptr; size_t remaining_len; GIT_MMAP_VALIDATE(out, len, prot, flags); /* writes cannot be emulated without handling pagefaults since write happens by * writing to mapped memory */ if (prot & GIT_PROT_WRITE) { git_error_set(GIT_ERROR_OS, "trying to map %s-writeable", ((flags & GIT_MAP_TYPE) == GIT_MAP_SHARED) ? "shared": "private"); return -1; } if (!git__is_ssizet(len)) { errno = EINVAL; return -1; } out->len = 0; out->data = git__malloc(len); GIT_ERROR_CHECK_ALLOC(out->data); remaining_len = len; ptr = (const char *)out->data; while (remaining_len > 0) { ssize_t nb; HANDLE_EINTR(nb, p_pread(fd, (void *)ptr, remaining_len, offset)); if (nb <= 0) { git_error_set(GIT_ERROR_OS, "mmap emulation failed"); git__free(out->data); out->data = NULL; return -1; } ptr += nb; offset += nb; remaining_len -= nb; } out->len = len; return 0; } int p_munmap(git_map *map) { GIT_ASSERT_ARG(map); git__free(map->data); /* Initializing will help debug use-after-free */ map->len = 0; map->data = NULL; return 0; } #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/midx.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "midx.h" #include "array.h" #include "buffer.h" #include "filebuf.h" #include "futils.h" #include "hash.h" #include "odb.h" #include "pack.h" #include "path.h" #include "repository.h" #define MIDX_SIGNATURE 0x4d494458 /* "MIDX" */ #define MIDX_VERSION 1 #define MIDX_OBJECT_ID_VERSION 1 struct git_midx_header { uint32_t signature; uint8_t version; uint8_t object_id_version; uint8_t chunks; uint8_t base_midx_files; uint32_t packfiles; }; #define MIDX_PACKFILE_NAMES_ID 0x504e414d /* "PNAM" */ #define MIDX_OID_FANOUT_ID 0x4f494446 /* "OIDF" */ #define MIDX_OID_LOOKUP_ID 0x4f49444c /* "OIDL" */ #define MIDX_OBJECT_OFFSETS_ID 0x4f4f4646 /* "OOFF" */ #define MIDX_OBJECT_LARGE_OFFSETS_ID 0x4c4f4646 /* "LOFF" */ struct git_midx_chunk { off64_t offset; size_t length; }; typedef int (*midx_write_cb)(const char *buf, size_t size, void *cb_data); static int midx_error(const char *message) { git_error_set(GIT_ERROR_ODB, "invalid multi-pack-index file - %s", message); return -1; } static int midx_parse_packfile_names( git_midx_file *idx, const unsigned char *data, uint32_t packfiles, struct git_midx_chunk *chunk) { int error; uint32_t i; char *packfile_name = (char *)(data + chunk->offset); size_t chunk_size = chunk->length, len; if (chunk->offset == 0) return midx_error("missing Packfile Names chunk"); if (chunk->length == 0) return midx_error("empty Packfile Names chunk"); if ((error = git_vector_init(&idx->packfile_names, packfiles, git__strcmp_cb)) < 0) return error; for (i = 0; i < packfiles; ++i) { len = p_strnlen(packfile_name, chunk_size); if (len == 0) return midx_error("empty packfile name"); if (len + 1 > chunk_size) return midx_error("unterminated packfile name"); git_vector_insert(&idx->packfile_names, packfile_name); if (i && strcmp(git_vector_get(&idx->packfile_names, i - 1), packfile_name) >= 0) return midx_error("packfile names are not sorted"); if (strlen(packfile_name) <= strlen(".idx") || git__suffixcmp(packfile_name, ".idx") != 0) return midx_error("non-.idx packfile name"); if (strchr(packfile_name, '/') != NULL || strchr(packfile_name, '\\') != NULL) return midx_error("non-local packfile"); packfile_name += len + 1; chunk_size -= len + 1; } return 0; } static int midx_parse_oid_fanout( git_midx_file *idx, const unsigned char *data, struct git_midx_chunk *chunk_oid_fanout) { uint32_t i, nr; if (chunk_oid_fanout->offset == 0) return midx_error("missing OID Fanout chunk"); if (chunk_oid_fanout->length == 0) return midx_error("empty OID Fanout chunk"); if (chunk_oid_fanout->length != 256 * 4) return midx_error("OID Fanout chunk has wrong length"); idx->oid_fanout = (const uint32_t *)(data + chunk_oid_fanout->offset); nr = 0; for (i = 0; i < 256; ++i) { uint32_t n = ntohl(idx->oid_fanout[i]); if (n < nr) return midx_error("index is non-monotonic"); nr = n; } idx->num_objects = nr; return 0; } static int midx_parse_oid_lookup( git_midx_file *idx, const unsigned char *data, struct git_midx_chunk *chunk_oid_lookup) { uint32_t i; git_oid *oid, *prev_oid, zero_oid = {{0}}; if (chunk_oid_lookup->offset == 0) return midx_error("missing OID Lookup chunk"); if (chunk_oid_lookup->length == 0) return midx_error("empty OID Lookup chunk"); if (chunk_oid_lookup->length != idx->num_objects * GIT_OID_RAWSZ) return midx_error("OID Lookup chunk has wrong length"); idx->oid_lookup = oid = (git_oid *)(data + chunk_oid_lookup->offset); prev_oid = &zero_oid; for (i = 0; i < idx->num_objects; ++i, ++oid) { if (git_oid_cmp(prev_oid, oid) >= 0) return midx_error("OID Lookup index is non-monotonic"); prev_oid = oid; } return 0; } static int midx_parse_object_offsets( git_midx_file *idx, const unsigned char *data, struct git_midx_chunk *chunk_object_offsets) { if (chunk_object_offsets->offset == 0) return midx_error("missing Object Offsets chunk"); if (chunk_object_offsets->length == 0) return midx_error("empty Object Offsets chunk"); if (chunk_object_offsets->length != idx->num_objects * 8) return midx_error("Object Offsets chunk has wrong length"); idx->object_offsets = data + chunk_object_offsets->offset; return 0; } static int midx_parse_object_large_offsets( git_midx_file *idx, const unsigned char *data, struct git_midx_chunk *chunk_object_large_offsets) { if (chunk_object_large_offsets->length == 0) return 0; if (chunk_object_large_offsets->length % 8 != 0) return midx_error("malformed Object Large Offsets chunk"); idx->object_large_offsets = data + chunk_object_large_offsets->offset; idx->num_object_large_offsets = chunk_object_large_offsets->length / 8; return 0; } int git_midx_parse( git_midx_file *idx, const unsigned char *data, size_t size) { struct git_midx_header *hdr; const unsigned char *chunk_hdr; struct git_midx_chunk *last_chunk; uint32_t i; off64_t last_chunk_offset, chunk_offset, trailer_offset; git_oid idx_checksum = {{0}}; int error; struct git_midx_chunk chunk_packfile_names = {0}, chunk_oid_fanout = {0}, chunk_oid_lookup = {0}, chunk_object_offsets = {0}, chunk_object_large_offsets = {0}; GIT_ASSERT_ARG(idx); if (size < sizeof(struct git_midx_header) + GIT_OID_RAWSZ) return midx_error("multi-pack index is too short"); hdr = ((struct git_midx_header *)data); if (hdr->signature != htonl(MIDX_SIGNATURE) || hdr->version != MIDX_VERSION || hdr->object_id_version != MIDX_OBJECT_ID_VERSION) { return midx_error("unsupported multi-pack index version"); } if (hdr->chunks == 0) return midx_error("no chunks in multi-pack index"); /* * The very first chunk's offset should be after the header, all the chunk * headers, and a special zero chunk. */ last_chunk_offset = sizeof(struct git_midx_header) + (1 + hdr->chunks) * 12; trailer_offset = size - GIT_OID_RAWSZ; if (trailer_offset < last_chunk_offset) return midx_error("wrong index size"); git_oid_cpy(&idx->checksum, (git_oid *)(data + trailer_offset)); if (git_hash_buf(&idx_checksum, data, (size_t)trailer_offset) < 0) return midx_error("could not calculate signature"); if (!git_oid_equal(&idx_checksum, &idx->checksum)) return midx_error("index signature mismatch"); chunk_hdr = data + sizeof(struct git_midx_header); last_chunk = NULL; for (i = 0; i < hdr->chunks; ++i, chunk_hdr += 12) { chunk_offset = ((off64_t)ntohl(*((uint32_t *)(chunk_hdr + 4)))) << 32 | ((off64_t)ntohl(*((uint32_t *)(chunk_hdr + 8)))); if (chunk_offset < last_chunk_offset) return midx_error("chunks are non-monotonic"); if (chunk_offset >= trailer_offset) return midx_error("chunks extend beyond the trailer"); if (last_chunk != NULL) last_chunk->length = (size_t)(chunk_offset - last_chunk_offset); last_chunk_offset = chunk_offset; switch (ntohl(*((uint32_t *)(chunk_hdr + 0)))) { case MIDX_PACKFILE_NAMES_ID: chunk_packfile_names.offset = last_chunk_offset; last_chunk = &chunk_packfile_names; break; case MIDX_OID_FANOUT_ID: chunk_oid_fanout.offset = last_chunk_offset; last_chunk = &chunk_oid_fanout; break; case MIDX_OID_LOOKUP_ID: chunk_oid_lookup.offset = last_chunk_offset; last_chunk = &chunk_oid_lookup; break; case MIDX_OBJECT_OFFSETS_ID: chunk_object_offsets.offset = last_chunk_offset; last_chunk = &chunk_object_offsets; break; case MIDX_OBJECT_LARGE_OFFSETS_ID: chunk_object_large_offsets.offset = last_chunk_offset; last_chunk = &chunk_object_large_offsets; break; default: return midx_error("unrecognized chunk ID"); } } last_chunk->length = (size_t)(trailer_offset - last_chunk_offset); error = midx_parse_packfile_names( idx, data, ntohl(hdr->packfiles), &chunk_packfile_names); if (error < 0) return error; error = midx_parse_oid_fanout(idx, data, &chunk_oid_fanout); if (error < 0) return error; error = midx_parse_oid_lookup(idx, data, &chunk_oid_lookup); if (error < 0) return error; error = midx_parse_object_offsets(idx, data, &chunk_object_offsets); if (error < 0) return error; error = midx_parse_object_large_offsets(idx, data, &chunk_object_large_offsets); if (error < 0) return error; return 0; } int git_midx_open( git_midx_file **idx_out, const char *path) { git_midx_file *idx; git_file fd = -1; size_t idx_size; struct stat st; int error; /* TODO: properly open the file without access time using O_NOATIME */ fd = git_futils_open_ro(path); if (fd < 0) return fd; if (p_fstat(fd, &st) < 0) { p_close(fd); git_error_set(GIT_ERROR_ODB, "multi-pack-index file not found - '%s'", path); return -1; } if (!S_ISREG(st.st_mode) || !git__is_sizet(st.st_size)) { p_close(fd); git_error_set(GIT_ERROR_ODB, "invalid pack index '%s'", path); return -1; } idx_size = (size_t)st.st_size; idx = git__calloc(1, sizeof(git_midx_file)); GIT_ERROR_CHECK_ALLOC(idx); error = git_buf_sets(&idx->filename, path); if (error < 0) return error; error = git_futils_mmap_ro(&idx->index_map, fd, 0, idx_size); p_close(fd); if (error < 0) { git_midx_free(idx); return error; } if ((error = git_midx_parse(idx, idx->index_map.data, idx_size)) < 0) { git_midx_free(idx); return error; } *idx_out = idx; return 0; } bool git_midx_needs_refresh( const git_midx_file *idx, const char *path) { git_file fd = -1; struct stat st; ssize_t bytes_read; git_oid idx_checksum = {{0}}; /* TODO: properly open the file without access time using O_NOATIME */ fd = git_futils_open_ro(path); if (fd < 0) return true; if (p_fstat(fd, &st) < 0) { p_close(fd); return true; } if (!S_ISREG(st.st_mode) || !git__is_sizet(st.st_size) || (size_t)st.st_size != idx->index_map.len) { p_close(fd); return true; } bytes_read = p_pread(fd, &idx_checksum, GIT_OID_RAWSZ, st.st_size - GIT_OID_RAWSZ); p_close(fd); if (bytes_read != GIT_OID_RAWSZ) return true; return !git_oid_equal(&idx_checksum, &idx->checksum); } int git_midx_entry_find( git_midx_entry *e, git_midx_file *idx, const git_oid *short_oid, size_t len) { int pos, found = 0; size_t pack_index; uint32_t hi, lo; const git_oid *current = NULL; const unsigned char *object_offset; off64_t offset; GIT_ASSERT_ARG(idx); hi = ntohl(idx->oid_fanout[(int)short_oid->id[0]]); lo = ((short_oid->id[0] == 0x0) ? 0 : ntohl(idx->oid_fanout[(int)short_oid->id[0] - 1])); pos = git_pack__lookup_sha1(idx->oid_lookup, GIT_OID_RAWSZ, lo, hi, short_oid->id); if (pos >= 0) { /* An object matching exactly the oid was found */ found = 1; current = idx->oid_lookup + pos; } else { /* No object was found */ /* pos refers to the object with the "closest" oid to short_oid */ pos = -1 - pos; if (pos < (int)idx->num_objects) { current = idx->oid_lookup + pos; if (!git_oid_ncmp(short_oid, current, len)) found = 1; } } if (found && len != GIT_OID_HEXSZ && pos + 1 < (int)idx->num_objects) { /* Check for ambiguousity */ const git_oid *next = current + 1; if (!git_oid_ncmp(short_oid, next, len)) { found = 2; } } if (!found) return git_odb__error_notfound("failed to find offset for multi-pack index entry", short_oid, len); if (found > 1) return git_odb__error_ambiguous("found multiple offsets for multi-pack index entry"); object_offset = idx->object_offsets + pos * 8; offset = ntohl(*((uint32_t *)(object_offset + 4))); if (offset & 0x80000000) { uint32_t object_large_offsets_pos = offset & 0x7fffffff; const unsigned char *object_large_offsets_index = idx->object_large_offsets; /* Make sure we're not being sent out of bounds */ if (object_large_offsets_pos >= idx->num_object_large_offsets) return git_odb__error_notfound("invalid index into the object large offsets table", short_oid, len); object_large_offsets_index += 8 * object_large_offsets_pos; offset = (((uint64_t)ntohl(*((uint32_t *)(object_large_offsets_index + 0)))) << 32) | ntohl(*((uint32_t *)(object_large_offsets_index + 4))); } pack_index = ntohl(*((uint32_t *)(object_offset + 0))); if (pack_index >= git_vector_length(&idx->packfile_names)) return midx_error("invalid index into the packfile names table"); e->pack_index = pack_index; e->offset = offset; git_oid_cpy(&e->sha1, current); return 0; } int git_midx_foreach_entry( git_midx_file *idx, git_odb_foreach_cb cb, void *data) { size_t i; int error; GIT_ASSERT_ARG(idx); for (i = 0; i < idx->num_objects; ++i) { if ((error = cb(&idx->oid_lookup[i], data)) != 0) return git_error_set_after_callback(error); } return error; } int git_midx_close(git_midx_file *idx) { GIT_ASSERT_ARG(idx); if (idx->index_map.data) git_futils_mmap_free(&idx->index_map); git_vector_free(&idx->packfile_names); return 0; } void git_midx_free(git_midx_file *idx) { if (!idx) return; git_buf_dispose(&idx->filename); git_midx_close(idx); git__free(idx); } static int packfile__cmp(const void *a_, const void *b_) { const struct git_pack_file *a = a_; const struct git_pack_file *b = b_; return strcmp(a->pack_name, b->pack_name); } int git_midx_writer_new( git_midx_writer **out, const char *pack_dir) { git_midx_writer *w = git__calloc(1, sizeof(git_midx_writer)); GIT_ERROR_CHECK_ALLOC(w); if (git_buf_sets(&w->pack_dir, pack_dir) < 0) { git__free(w); return -1; } git_path_squash_slashes(&w->pack_dir); if (git_vector_init(&w->packs, 0, packfile__cmp) < 0) { git_buf_dispose(&w->pack_dir); git__free(w); return -1; } *out = w; return 0; } void git_midx_writer_free(git_midx_writer *w) { struct git_pack_file *p; size_t i; if (!w) return; git_vector_foreach (&w->packs, i, p) git_mwindow_put_pack(p); git_vector_free(&w->packs); git_buf_dispose(&w->pack_dir); git__free(w); } int git_midx_writer_add( git_midx_writer *w, const char *idx_path) { git_buf idx_path_buf = GIT_BUF_INIT; int error; struct git_pack_file *p; error = git_path_prettify(&idx_path_buf, idx_path, git_buf_cstr(&w->pack_dir)); if (error < 0) return error; error = git_mwindow_get_pack(&p, git_buf_cstr(&idx_path_buf)); git_buf_dispose(&idx_path_buf); if (error < 0) return error; error = git_vector_insert(&w->packs, p); if (error < 0) { git_mwindow_put_pack(p); return error; } return 0; } typedef git_array_t(git_midx_entry) object_entry_array_t; struct object_entry_cb_state { uint32_t pack_index; object_entry_array_t *object_entries_array; }; static int object_entry__cb(const git_oid *oid, off64_t offset, void *data) { struct object_entry_cb_state *state = (struct object_entry_cb_state *)data; git_midx_entry *entry = git_array_alloc(*state->object_entries_array); GIT_ERROR_CHECK_ALLOC(entry); git_oid_cpy(&entry->sha1, oid); entry->offset = offset; entry->pack_index = state->pack_index; return 0; } static int object_entry__cmp(const void *a_, const void *b_) { const git_midx_entry *a = (const git_midx_entry *)a_; const git_midx_entry *b = (const git_midx_entry *)b_; return git_oid_cmp(&a->sha1, &b->sha1); } static int write_offset(off64_t offset, midx_write_cb write_cb, void *cb_data) { int error; uint32_t word; word = htonl((uint32_t)((offset >> 32) & 0xffffffffu)); error = write_cb((const char *)&word, sizeof(word), cb_data); if (error < 0) return error; word = htonl((uint32_t)((offset >> 0) & 0xffffffffu)); error = write_cb((const char *)&word, sizeof(word), cb_data); if (error < 0) return error; return 0; } static int write_chunk_header(int chunk_id, off64_t offset, midx_write_cb write_cb, void *cb_data) { uint32_t word = htonl(chunk_id); int error = write_cb((const char *)&word, sizeof(word), cb_data); if (error < 0) return error; return write_offset(offset, write_cb, cb_data); return 0; } static int midx_write_buf(const char *buf, size_t size, void *data) { git_buf *b = (git_buf *)data; return git_buf_put(b, buf, size); } struct midx_write_hash_context { midx_write_cb write_cb; void *cb_data; git_hash_ctx *ctx; }; static int midx_write_hash(const char *buf, size_t size, void *data) { struct midx_write_hash_context *ctx = (struct midx_write_hash_context *)data; int error; error = git_hash_update(ctx->ctx, buf, size); if (error < 0) return error; return ctx->write_cb(buf, size, ctx->cb_data); } static int midx_write( git_midx_writer *w, midx_write_cb write_cb, void *cb_data) { int error = 0; size_t i; struct git_pack_file *p; struct git_midx_header hdr = {0}; uint32_t oid_fanout_count; uint32_t object_large_offsets_count; uint32_t oid_fanout[256]; off64_t offset; git_buf packfile_names = GIT_BUF_INIT, oid_lookup = GIT_BUF_INIT, object_offsets = GIT_BUF_INIT, object_large_offsets = GIT_BUF_INIT; git_oid idx_checksum = {{0}}; git_midx_entry *entry; object_entry_array_t object_entries_array = GIT_ARRAY_INIT; git_vector object_entries = GIT_VECTOR_INIT; git_hash_ctx ctx; struct midx_write_hash_context hash_cb_data = {0}; hdr.signature = htonl(MIDX_SIGNATURE); hdr.version = MIDX_VERSION; hdr.object_id_version = MIDX_OBJECT_ID_VERSION; hdr.base_midx_files = 0; hash_cb_data.write_cb = write_cb; hash_cb_data.cb_data = cb_data; hash_cb_data.ctx = &ctx; error = git_hash_ctx_init(&ctx); if (error < 0) return error; cb_data = &hash_cb_data; write_cb = midx_write_hash; git_vector_sort(&w->packs); git_vector_foreach (&w->packs, i, p) { git_buf relative_index = GIT_BUF_INIT; struct object_entry_cb_state state = {0}; size_t path_len; state.pack_index = (uint32_t)i; state.object_entries_array = &object_entries_array; error = git_buf_sets(&relative_index, p->pack_name); if (error < 0) goto cleanup; error = git_path_make_relative(&relative_index, git_buf_cstr(&w->pack_dir)); if (error < 0) { git_buf_dispose(&relative_index); goto cleanup; } path_len = git_buf_len(&relative_index); if (path_len <= strlen(".pack") || git__suffixcmp(git_buf_cstr(&relative_index), ".pack") != 0) { git_buf_dispose(&relative_index); git_error_set(GIT_ERROR_INVALID, "invalid packfile name: '%s'", p->pack_name); error = -1; goto cleanup; } path_len -= strlen(".pack"); git_buf_put(&packfile_names, git_buf_cstr(&relative_index), path_len); git_buf_puts(&packfile_names, ".idx"); git_buf_putc(&packfile_names, '\0'); git_buf_dispose(&relative_index); error = git_pack_foreach_entry_offset(p, object_entry__cb, &state); if (error < 0) goto cleanup; } /* Sort the object entries. */ error = git_vector_init(&object_entries, git_array_size(object_entries_array), object_entry__cmp); if (error < 0) goto cleanup; git_array_foreach (object_entries_array, i, entry) { if ((error = git_vector_set(NULL, &object_entries, i, entry)) < 0) goto cleanup; } git_vector_set_sorted(&object_entries, 0); git_vector_sort(&object_entries); git_vector_uniq(&object_entries, NULL); /* Pad the packfile names so it is a multiple of four. */ while (git_buf_len(&packfile_names) & 3) git_buf_putc(&packfile_names, '\0'); /* Fill the OID Fanout table. */ oid_fanout_count = 0; for (i = 0; i < 256; i++) { while (oid_fanout_count < git_vector_length(&object_entries) && ((const git_midx_entry *)git_vector_get(&object_entries, oid_fanout_count))->sha1.id[0] <= i) ++oid_fanout_count; oid_fanout[i] = htonl(oid_fanout_count); } /* Fill the OID Lookup table. */ git_vector_foreach (&object_entries, i, entry) { error = git_buf_put(&oid_lookup, (const char *)&entry->sha1, sizeof(entry->sha1)); if (error < 0) goto cleanup; } /* Fill the Object Offsets and Object Large Offsets tables. */ object_large_offsets_count = 0; git_vector_foreach (&object_entries, i, entry) { uint32_t word; word = htonl((uint32_t)entry->pack_index); error = git_buf_put(&object_offsets, (const char *)&word, sizeof(word)); if (error < 0) goto cleanup; if (entry->offset >= 0x80000000l) { word = htonl(0x80000000u | object_large_offsets_count++); if ((error = write_offset(entry->offset, midx_write_buf, &object_large_offsets)) < 0) goto cleanup; } else { word = htonl((uint32_t)entry->offset & 0x7fffffffu); } error = git_buf_put(&object_offsets, (const char *)&word, sizeof(word)); if (error < 0) goto cleanup; } /* Write the header. */ hdr.packfiles = htonl((uint32_t)git_vector_length(&w->packs)); hdr.chunks = 4; if (git_buf_len(&object_large_offsets) > 0) hdr.chunks++; error = write_cb((const char *)&hdr, sizeof(hdr), cb_data); if (error < 0) goto cleanup; /* Write the chunk headers. */ offset = sizeof(hdr) + (hdr.chunks + 1) * 12; error = write_chunk_header(MIDX_PACKFILE_NAMES_ID, offset, write_cb, cb_data); if (error < 0) goto cleanup; offset += git_buf_len(&packfile_names); error = write_chunk_header(MIDX_OID_FANOUT_ID, offset, write_cb, cb_data); if (error < 0) goto cleanup; offset += sizeof(oid_fanout); error = write_chunk_header(MIDX_OID_LOOKUP_ID, offset, write_cb, cb_data); if (error < 0) goto cleanup; offset += git_buf_len(&oid_lookup); error = write_chunk_header(MIDX_OBJECT_OFFSETS_ID, offset, write_cb, cb_data); if (error < 0) goto cleanup; offset += git_buf_len(&object_offsets); if (git_buf_len(&object_large_offsets) > 0) { error = write_chunk_header(MIDX_OBJECT_LARGE_OFFSETS_ID, offset, write_cb, cb_data); if (error < 0) goto cleanup; offset += git_buf_len(&object_large_offsets); } error = write_chunk_header(0, offset, write_cb, cb_data); if (error < 0) goto cleanup; /* Write all the chunks. */ error = write_cb(git_buf_cstr(&packfile_names), git_buf_len(&packfile_names), cb_data); if (error < 0) goto cleanup; error = write_cb((const char *)oid_fanout, sizeof(oid_fanout), cb_data); if (error < 0) goto cleanup; error = write_cb(git_buf_cstr(&oid_lookup), git_buf_len(&oid_lookup), cb_data); if (error < 0) goto cleanup; error = write_cb(git_buf_cstr(&object_offsets), git_buf_len(&object_offsets), cb_data); if (error < 0) goto cleanup; error = write_cb(git_buf_cstr(&object_large_offsets), git_buf_len(&object_large_offsets), cb_data); if (error < 0) goto cleanup; /* Finalize the checksum and write the trailer. */ error = git_hash_final(&idx_checksum, &ctx); if (error < 0) goto cleanup; error = write_cb((const char *)&idx_checksum, sizeof(idx_checksum), cb_data); if (error < 0) goto cleanup; cleanup: git_array_clear(object_entries_array); git_vector_free(&object_entries); git_buf_dispose(&packfile_names); git_buf_dispose(&oid_lookup); git_buf_dispose(&object_offsets); git_buf_dispose(&object_large_offsets); git_hash_ctx_cleanup(&ctx); return error; } static int midx_write_filebuf(const char *buf, size_t size, void *data) { git_filebuf *f = (git_filebuf *)data; return git_filebuf_write(f, buf, size); } int git_midx_writer_commit( git_midx_writer *w) { int error; int filebuf_flags = GIT_FILEBUF_DO_NOT_BUFFER; git_buf midx_path = GIT_BUF_INIT; git_filebuf output = GIT_FILEBUF_INIT; error = git_buf_joinpath(&midx_path, git_buf_cstr(&w->pack_dir), "multi-pack-index"); if (error < 0) return error; if (git_repository__fsync_gitdir) filebuf_flags |= GIT_FILEBUF_FSYNC; error = git_filebuf_open(&output, git_buf_cstr(&midx_path), filebuf_flags, 0644); git_buf_dispose(&midx_path); if (error < 0) return error; error = midx_write(w, midx_write_filebuf, &output); if (error < 0) { git_filebuf_cleanup(&output); return error; } return git_filebuf_commit(&output); } int git_midx_writer_dump( git_buf *midx, git_midx_writer *w) { return midx_write(w, midx_write_buf, midx); }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/config.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "config.h" #include "git2/config.h" #include "git2/sys/config.h" #include "config_backend.h" #include "regexp.h" #include "sysdir.h" #include "transaction.h" #include "vector.h" #if GIT_WIN32 # include <windows.h> #endif #include <ctype.h> void git_config_entry_free(git_config_entry *entry) { if (!entry) return; entry->free(entry); } typedef struct { git_refcount rc; git_config_backend *backend; git_config_level_t level; } backend_internal; static void backend_internal_free(backend_internal *internal) { git_config_backend *backend; backend = internal->backend; backend->free(backend); git__free(internal); } static void config_free(git_config *cfg) { size_t i; backend_internal *internal; for (i = 0; i < cfg->backends.length; ++i) { internal = git_vector_get(&cfg->backends, i); GIT_REFCOUNT_DEC(internal, backend_internal_free); } git_vector_free(&cfg->backends); git__memzero(cfg, sizeof(*cfg)); git__free(cfg); } void git_config_free(git_config *cfg) { if (cfg == NULL) return; GIT_REFCOUNT_DEC(cfg, config_free); } static int config_backend_cmp(const void *a, const void *b) { const backend_internal *bk_a = (const backend_internal *)(a); const backend_internal *bk_b = (const backend_internal *)(b); return bk_b->level - bk_a->level; } int git_config_new(git_config **out) { git_config *cfg; cfg = git__malloc(sizeof(git_config)); GIT_ERROR_CHECK_ALLOC(cfg); memset(cfg, 0x0, sizeof(git_config)); if (git_vector_init(&cfg->backends, 3, config_backend_cmp) < 0) { git__free(cfg); return -1; } *out = cfg; GIT_REFCOUNT_INC(cfg); return 0; } int git_config_add_file_ondisk( git_config *cfg, const char *path, git_config_level_t level, const git_repository *repo, int force) { git_config_backend *file = NULL; struct stat st; int res; GIT_ASSERT_ARG(cfg); GIT_ASSERT_ARG(path); res = p_stat(path, &st); if (res < 0 && errno != ENOENT && errno != ENOTDIR) { git_error_set(GIT_ERROR_CONFIG, "failed to stat '%s'", path); return -1; } if (git_config_backend_from_file(&file, path) < 0) return -1; if ((res = git_config_add_backend(cfg, file, level, repo, force)) < 0) { /* * free manually; the file is not owned by the config * instance yet and will not be freed on cleanup */ file->free(file); return res; } return 0; } int git_config_open_ondisk(git_config **out, const char *path) { int error; git_config *config; *out = NULL; if (git_config_new(&config) < 0) return -1; if ((error = git_config_add_file_ondisk(config, path, GIT_CONFIG_LEVEL_LOCAL, NULL, 0)) < 0) git_config_free(config); else *out = config; return error; } int git_config_snapshot(git_config **out, git_config *in) { int error = 0; size_t i; backend_internal *internal; git_config *config; *out = NULL; if (git_config_new(&config) < 0) return -1; git_vector_foreach(&in->backends, i, internal) { git_config_backend *b; if ((error = internal->backend->snapshot(&b, internal->backend)) < 0) break; if ((error = git_config_add_backend(config, b, internal->level, NULL, 0)) < 0) { b->free(b); break; } } if (error < 0) git_config_free(config); else *out = config; return error; } static int find_backend_by_level( backend_internal **out, const git_config *cfg, git_config_level_t level) { int pos = -1; backend_internal *internal; size_t i; /* when passing GIT_CONFIG_HIGHEST_LEVEL, the idea is to get the config backend * which has the highest level. As config backends are stored in a vector * sorted by decreasing order of level, getting the backend at position 0 * will do the job. */ if (level == GIT_CONFIG_HIGHEST_LEVEL) { pos = 0; } else { git_vector_foreach(&cfg->backends, i, internal) { if (internal->level == level) pos = (int)i; } } if (pos == -1) { git_error_set(GIT_ERROR_CONFIG, "no configuration exists for the given level '%i'", (int)level); return GIT_ENOTFOUND; } *out = git_vector_get(&cfg->backends, pos); return 0; } static int duplicate_level(void **old_raw, void *new_raw) { backend_internal **old = (backend_internal **)old_raw; GIT_UNUSED(new_raw); git_error_set(GIT_ERROR_CONFIG, "there already exists a configuration for the given level (%i)", (int)(*old)->level); return GIT_EEXISTS; } static void try_remove_existing_backend( git_config *cfg, git_config_level_t level) { int pos = -1; backend_internal *internal; size_t i; git_vector_foreach(&cfg->backends, i, internal) { if (internal->level == level) pos = (int)i; } if (pos == -1) return; internal = git_vector_get(&cfg->backends, pos); if (git_vector_remove(&cfg->backends, pos) < 0) return; GIT_REFCOUNT_DEC(internal, backend_internal_free); } static int git_config__add_internal( git_config *cfg, backend_internal *internal, git_config_level_t level, int force) { int result; /* delete existing config backend for level if it exists */ if (force) try_remove_existing_backend(cfg, level); if ((result = git_vector_insert_sorted(&cfg->backends, internal, &duplicate_level)) < 0) return result; git_vector_sort(&cfg->backends); internal->backend->cfg = cfg; GIT_REFCOUNT_INC(internal); return 0; } int git_config_open_global(git_config **cfg_out, git_config *cfg) { if (!git_config_open_level(cfg_out, cfg, GIT_CONFIG_LEVEL_XDG)) return 0; return git_config_open_level(cfg_out, cfg, GIT_CONFIG_LEVEL_GLOBAL); } int git_config_open_level( git_config **cfg_out, const git_config *cfg_parent, git_config_level_t level) { git_config *cfg; backend_internal *internal; int res; if ((res = find_backend_by_level(&internal, cfg_parent, level)) < 0) return res; if ((res = git_config_new(&cfg)) < 0) return res; if ((res = git_config__add_internal(cfg, internal, level, true)) < 0) { git_config_free(cfg); return res; } *cfg_out = cfg; return 0; } int git_config_add_backend( git_config *cfg, git_config_backend *backend, git_config_level_t level, const git_repository *repo, int force) { backend_internal *internal; int result; GIT_ASSERT_ARG(cfg); GIT_ASSERT_ARG(backend); GIT_ERROR_CHECK_VERSION(backend, GIT_CONFIG_BACKEND_VERSION, "git_config_backend"); if ((result = backend->open(backend, level, repo)) < 0) return result; internal = git__malloc(sizeof(backend_internal)); GIT_ERROR_CHECK_ALLOC(internal); memset(internal, 0x0, sizeof(backend_internal)); internal->backend = backend; internal->level = level; if ((result = git_config__add_internal(cfg, internal, level, force)) < 0) { git__free(internal); return result; } return 0; } /* * Loop over all the variables */ typedef struct { git_config_iterator parent; git_config_iterator *current; const git_config *cfg; git_regexp regex; size_t i; } all_iter; static int find_next_backend(size_t *out, const git_config *cfg, size_t i) { backend_internal *internal; for (; i > 0; --i) { internal = git_vector_get(&cfg->backends, i - 1); if (!internal || !internal->backend) continue; *out = i; return 0; } return -1; } static int all_iter_next(git_config_entry **entry, git_config_iterator *_iter) { all_iter *iter = (all_iter *) _iter; backend_internal *internal; git_config_backend *backend; size_t i; int error = 0; if (iter->current != NULL && (error = iter->current->next(entry, iter->current)) == 0) { return 0; } if (error < 0 && error != GIT_ITEROVER) return error; do { if (find_next_backend(&i, iter->cfg, iter->i) < 0) return GIT_ITEROVER; internal = git_vector_get(&iter->cfg->backends, i - 1); backend = internal->backend; iter->i = i - 1; if (iter->current) iter->current->free(iter->current); iter->current = NULL; error = backend->iterator(&iter->current, backend); if (error == GIT_ENOTFOUND) continue; if (error < 0) return error; error = iter->current->next(entry, iter->current); /* If this backend is empty, then keep going */ if (error == GIT_ITEROVER) continue; return error; } while(1); return GIT_ITEROVER; } static int all_iter_glob_next(git_config_entry **entry, git_config_iterator *_iter) { int error; all_iter *iter = (all_iter *) _iter; /* * We use the "normal" function to grab the next one across * backends and then apply the regex */ while ((error = all_iter_next(entry, _iter)) == 0) { /* skip non-matching keys if regexp was provided */ if (git_regexp_match(&iter->regex, (*entry)->name) != 0) continue; /* and simply return if we like the entry's name */ return 0; } return error; } static void all_iter_free(git_config_iterator *_iter) { all_iter *iter = (all_iter *) _iter; if (iter->current) iter->current->free(iter->current); git__free(iter); } static void all_iter_glob_free(git_config_iterator *_iter) { all_iter *iter = (all_iter *) _iter; git_regexp_dispose(&iter->regex); all_iter_free(_iter); } int git_config_iterator_new(git_config_iterator **out, const git_config *cfg) { all_iter *iter; iter = git__calloc(1, sizeof(all_iter)); GIT_ERROR_CHECK_ALLOC(iter); iter->parent.free = all_iter_free; iter->parent.next = all_iter_next; iter->i = cfg->backends.length; iter->cfg = cfg; *out = (git_config_iterator *) iter; return 0; } int git_config_iterator_glob_new(git_config_iterator **out, const git_config *cfg, const char *regexp) { all_iter *iter; int result; if (regexp == NULL) return git_config_iterator_new(out, cfg); iter = git__calloc(1, sizeof(all_iter)); GIT_ERROR_CHECK_ALLOC(iter); if ((result = git_regexp_compile(&iter->regex, regexp, 0)) < 0) { git__free(iter); return -1; } iter->parent.next = all_iter_glob_next; iter->parent.free = all_iter_glob_free; iter->i = cfg->backends.length; iter->cfg = cfg; *out = (git_config_iterator *) iter; return 0; } int git_config_foreach( const git_config *cfg, git_config_foreach_cb cb, void *payload) { return git_config_foreach_match(cfg, NULL, cb, payload); } int git_config_backend_foreach_match( git_config_backend *backend, const char *regexp, git_config_foreach_cb cb, void *payload) { git_config_entry *entry; git_config_iterator *iter; git_regexp regex; int error = 0; GIT_ASSERT_ARG(backend); GIT_ASSERT_ARG(cb); if (regexp && git_regexp_compile(&regex, regexp, 0) < 0) return -1; if ((error = backend->iterator(&iter, backend)) < 0) { iter = NULL; return -1; } while (!(iter->next(&entry, iter) < 0)) { /* skip non-matching keys if regexp was provided */ if (regexp && git_regexp_match(&regex, entry->name) != 0) continue; /* abort iterator on non-zero return value */ if ((error = cb(entry, payload)) != 0) { git_error_set_after_callback(error); break; } } if (regexp != NULL) git_regexp_dispose(&regex); iter->free(iter); return error; } int git_config_foreach_match( const git_config *cfg, const char *regexp, git_config_foreach_cb cb, void *payload) { int error; git_config_iterator *iter; git_config_entry *entry; if ((error = git_config_iterator_glob_new(&iter, cfg, regexp)) < 0) return error; while (!(error = git_config_next(&entry, iter))) { if ((error = cb(entry, payload)) != 0) { git_error_set_after_callback(error); break; } } git_config_iterator_free(iter); if (error == GIT_ITEROVER) error = 0; return error; } /************** * Setters **************/ typedef enum { BACKEND_USE_SET, BACKEND_USE_DELETE } backend_use; static const char *uses[] = { "set", "delete" }; static int get_backend_for_use(git_config_backend **out, git_config *cfg, const char *name, backend_use use) { size_t i; backend_internal *backend; *out = NULL; if (git_vector_length(&cfg->backends) == 0) { git_error_set(GIT_ERROR_CONFIG, "cannot %s value for '%s' when no config backends exist", uses[use], name); return GIT_ENOTFOUND; } git_vector_foreach(&cfg->backends, i, backend) { if (!backend->backend->readonly) { *out = backend->backend; return 0; } } git_error_set(GIT_ERROR_CONFIG, "cannot %s value for '%s' when all config backends are readonly", uses[use], name); return GIT_ENOTFOUND; } int git_config_delete_entry(git_config *cfg, const char *name) { git_config_backend *backend; if (get_backend_for_use(&backend, cfg, name, BACKEND_USE_DELETE) < 0) return GIT_ENOTFOUND; return backend->del(backend, name); } int git_config_set_int64(git_config *cfg, const char *name, int64_t value) { char str_value[32]; /* All numbers should fit in here */ p_snprintf(str_value, sizeof(str_value), "%" PRId64, value); return git_config_set_string(cfg, name, str_value); } int git_config_set_int32(git_config *cfg, const char *name, int32_t value) { return git_config_set_int64(cfg, name, (int64_t)value); } int git_config_set_bool(git_config *cfg, const char *name, int value) { return git_config_set_string(cfg, name, value ? "true" : "false"); } int git_config_set_string(git_config *cfg, const char *name, const char *value) { int error; git_config_backend *backend; if (!value) { git_error_set(GIT_ERROR_CONFIG, "the value to set cannot be NULL"); return -1; } if (get_backend_for_use(&backend, cfg, name, BACKEND_USE_SET) < 0) return GIT_ENOTFOUND; error = backend->set(backend, name, value); if (!error && GIT_REFCOUNT_OWNER(cfg) != NULL) git_repository__configmap_lookup_cache_clear(GIT_REFCOUNT_OWNER(cfg)); return error; } int git_config__update_entry( git_config *config, const char *key, const char *value, bool overwrite_existing, bool only_if_existing) { int error = 0; git_config_entry *ce = NULL; if ((error = git_config__lookup_entry(&ce, config, key, false)) < 0) return error; if (!ce && only_if_existing) /* entry doesn't exist */ return 0; if (ce && !overwrite_existing) /* entry would be overwritten */ return 0; if (value && ce && ce->value && !strcmp(ce->value, value)) /* no change */ return 0; if (!value && (!ce || !ce->value)) /* asked to delete absent entry */ return 0; if (!value) error = git_config_delete_entry(config, key); else error = git_config_set_string(config, key, value); git_config_entry_free(ce); return error; } /*********** * Getters ***********/ static int config_error_notfound(const char *name) { git_error_set(GIT_ERROR_CONFIG, "config value '%s' was not found", name); return GIT_ENOTFOUND; } enum { GET_ALL_ERRORS = 0, GET_NO_MISSING = 1, GET_NO_ERRORS = 2 }; static int get_entry( git_config_entry **out, const git_config *cfg, const char *name, bool normalize_name, int want_errors) { int res = GIT_ENOTFOUND; const char *key = name; char *normalized = NULL; size_t i; backend_internal *internal; *out = NULL; if (normalize_name) { if ((res = git_config__normalize_name(name, &normalized)) < 0) goto cleanup; key = normalized; } res = GIT_ENOTFOUND; git_vector_foreach(&cfg->backends, i, internal) { if (!internal || !internal->backend) continue; res = internal->backend->get(internal->backend, key, out); if (res != GIT_ENOTFOUND) break; } git__free(normalized); cleanup: if (res == GIT_ENOTFOUND) res = (want_errors > GET_ALL_ERRORS) ? 0 : config_error_notfound(name); else if (res && (want_errors == GET_NO_ERRORS)) { git_error_clear(); res = 0; } return res; } int git_config_get_entry( git_config_entry **out, const git_config *cfg, const char *name) { return get_entry(out, cfg, name, true, GET_ALL_ERRORS); } int git_config__lookup_entry( git_config_entry **out, const git_config *cfg, const char *key, bool no_errors) { return get_entry( out, cfg, key, false, no_errors ? GET_NO_ERRORS : GET_NO_MISSING); } int git_config_get_mapped( int *out, const git_config *cfg, const char *name, const git_configmap *maps, size_t map_n) { git_config_entry *entry; int ret; if ((ret = get_entry(&entry, cfg, name, true, GET_ALL_ERRORS)) < 0) return ret; ret = git_config_lookup_map_value(out, maps, map_n, entry->value); git_config_entry_free(entry); return ret; } int git_config_get_int64(int64_t *out, const git_config *cfg, const char *name) { git_config_entry *entry; int ret; if ((ret = get_entry(&entry, cfg, name, true, GET_ALL_ERRORS)) < 0) return ret; ret = git_config_parse_int64(out, entry->value); git_config_entry_free(entry); return ret; } int git_config_get_int32(int32_t *out, const git_config *cfg, const char *name) { git_config_entry *entry; int ret; if ((ret = get_entry(&entry, cfg, name, true, GET_ALL_ERRORS)) < 0) return ret; ret = git_config_parse_int32(out, entry->value); git_config_entry_free(entry); return ret; } int git_config_get_bool(int *out, const git_config *cfg, const char *name) { git_config_entry *entry; int ret; if ((ret = get_entry(&entry, cfg, name, true, GET_ALL_ERRORS)) < 0) return ret; ret = git_config_parse_bool(out, entry->value); git_config_entry_free(entry); return ret; } static int is_readonly(const git_config *cfg) { size_t i; backend_internal *internal; git_vector_foreach(&cfg->backends, i, internal) { if (!internal || !internal->backend) continue; if (!internal->backend->readonly) return 0; } return 1; } int git_config_get_path(git_buf *out, const git_config *cfg, const char *name) { git_config_entry *entry; int error; if ((error = get_entry(&entry, cfg, name, true, GET_ALL_ERRORS)) < 0) return error; error = git_config_parse_path(out, entry->value); git_config_entry_free(entry); return error; } int git_config_get_string( const char **out, const git_config *cfg, const char *name) { git_config_entry *entry; int ret; if (!is_readonly(cfg)) { git_error_set(GIT_ERROR_CONFIG, "get_string called on a live config object"); return -1; } ret = get_entry(&entry, cfg, name, true, GET_ALL_ERRORS); *out = !ret ? (entry->value ? entry->value : "") : NULL; git_config_entry_free(entry); return ret; } int git_config_get_string_buf( git_buf *out, const git_config *cfg, const char *name) { git_config_entry *entry; int ret; const char *str; if ((ret = git_buf_sanitize(out)) < 0) return ret; ret = get_entry(&entry, cfg, name, true, GET_ALL_ERRORS); str = !ret ? (entry->value ? entry->value : "") : NULL; if (str) ret = git_buf_puts(out, str); git_config_entry_free(entry); return ret; } char *git_config__get_string_force( const git_config *cfg, const char *key, const char *fallback_value) { git_config_entry *entry; char *ret; get_entry(&entry, cfg, key, false, GET_NO_ERRORS); ret = (entry && entry->value) ? git__strdup(entry->value) : fallback_value ? git__strdup(fallback_value) : NULL; git_config_entry_free(entry); return ret; } int git_config__get_bool_force( const git_config *cfg, const char *key, int fallback_value) { int val = fallback_value; git_config_entry *entry; get_entry(&entry, cfg, key, false, GET_NO_ERRORS); if (entry && git_config_parse_bool(&val, entry->value) < 0) git_error_clear(); git_config_entry_free(entry); return val; } int git_config__get_int_force( const git_config *cfg, const char *key, int fallback_value) { int32_t val = (int32_t)fallback_value; git_config_entry *entry; get_entry(&entry, cfg, key, false, GET_NO_ERRORS); if (entry && git_config_parse_int32(&val, entry->value) < 0) git_error_clear(); git_config_entry_free(entry); return (int)val; } int git_config_get_multivar_foreach( const git_config *cfg, const char *name, const char *regexp, git_config_foreach_cb cb, void *payload) { int err, found; git_config_iterator *iter; git_config_entry *entry; if ((err = git_config_multivar_iterator_new(&iter, cfg, name, regexp)) < 0) return err; found = 0; while ((err = iter->next(&entry, iter)) == 0) { found = 1; if ((err = cb(entry, payload)) != 0) { git_error_set_after_callback(err); break; } } iter->free(iter); if (err == GIT_ITEROVER) err = 0; if (found == 0 && err == 0) err = config_error_notfound(name); return err; } typedef struct { git_config_iterator parent; git_config_iterator *iter; char *name; git_regexp regex; int have_regex; } multivar_iter; static int multivar_iter_next(git_config_entry **entry, git_config_iterator *_iter) { multivar_iter *iter = (multivar_iter *) _iter; int error = 0; while ((error = iter->iter->next(entry, iter->iter)) == 0) { if (git__strcmp(iter->name, (*entry)->name)) continue; if (!iter->have_regex) return 0; if (git_regexp_match(&iter->regex, (*entry)->value) == 0) return 0; } return error; } static void multivar_iter_free(git_config_iterator *_iter) { multivar_iter *iter = (multivar_iter *) _iter; iter->iter->free(iter->iter); git__free(iter->name); if (iter->have_regex) git_regexp_dispose(&iter->regex); git__free(iter); } int git_config_multivar_iterator_new(git_config_iterator **out, const git_config *cfg, const char *name, const char *regexp) { multivar_iter *iter = NULL; git_config_iterator *inner = NULL; int error; if ((error = git_config_iterator_new(&inner, cfg)) < 0) return error; iter = git__calloc(1, sizeof(multivar_iter)); GIT_ERROR_CHECK_ALLOC(iter); if ((error = git_config__normalize_name(name, &iter->name)) < 0) goto on_error; if (regexp != NULL) { if ((error = git_regexp_compile(&iter->regex, regexp, 0)) < 0) goto on_error; iter->have_regex = 1; } iter->iter = inner; iter->parent.free = multivar_iter_free; iter->parent.next = multivar_iter_next; *out = (git_config_iterator *) iter; return 0; on_error: inner->free(inner); git__free(iter); return error; } int git_config_set_multivar(git_config *cfg, const char *name, const char *regexp, const char *value) { git_config_backend *backend; if (get_backend_for_use(&backend, cfg, name, BACKEND_USE_DELETE) < 0) return GIT_ENOTFOUND; return backend->set_multivar(backend, name, regexp, value); } int git_config_delete_multivar(git_config *cfg, const char *name, const char *regexp) { git_config_backend *backend; if (get_backend_for_use(&backend, cfg, name, BACKEND_USE_DELETE) < 0) return GIT_ENOTFOUND; return backend->del_multivar(backend, name, regexp); } int git_config_next(git_config_entry **entry, git_config_iterator *iter) { return iter->next(entry, iter); } void git_config_iterator_free(git_config_iterator *iter) { if (iter == NULL) return; iter->free(iter); } int git_config_find_global(git_buf *path) { int error; if ((error = git_buf_sanitize(path)) < 0) return error; return git_sysdir_find_global_file(path, GIT_CONFIG_FILENAME_GLOBAL); } int git_config_find_xdg(git_buf *path) { int error; if ((error = git_buf_sanitize(path)) < 0) return error; return git_sysdir_find_xdg_file(path, GIT_CONFIG_FILENAME_XDG); } int git_config_find_system(git_buf *path) { int error; if ((error = git_buf_sanitize(path)) < 0) return error; return git_sysdir_find_system_file(path, GIT_CONFIG_FILENAME_SYSTEM); } int git_config_find_programdata(git_buf *path) { int ret; if ((ret = git_buf_sanitize(path)) < 0) return ret; ret = git_sysdir_find_programdata_file(path, GIT_CONFIG_FILENAME_PROGRAMDATA); if (ret != GIT_OK) return ret; return git_path_validate_system_file_ownership(path->ptr); } int git_config__global_location(git_buf *buf) { const git_buf *paths; const char *sep, *start; if (git_sysdir_get(&paths, GIT_SYSDIR_GLOBAL) < 0) return -1; /* no paths, so give up */ if (!paths || !git_buf_len(paths)) return -1; /* find unescaped separator or end of string */ for (sep = start = git_buf_cstr(paths); *sep; ++sep) { if (*sep == GIT_PATH_LIST_SEPARATOR && (sep <= start || sep[-1] != '\\')) break; } if (git_buf_set(buf, start, (size_t)(sep - start)) < 0) return -1; return git_buf_joinpath(buf, buf->ptr, GIT_CONFIG_FILENAME_GLOBAL); } int git_config_open_default(git_config **out) { int error; git_config *cfg = NULL; git_buf buf = GIT_BUF_INIT; if ((error = git_config_new(&cfg)) < 0) return error; if (!git_config_find_global(&buf) || !git_config__global_location(&buf)) { error = git_config_add_file_ondisk(cfg, buf.ptr, GIT_CONFIG_LEVEL_GLOBAL, NULL, 0); } if (!error && !git_config_find_xdg(&buf)) error = git_config_add_file_ondisk(cfg, buf.ptr, GIT_CONFIG_LEVEL_XDG, NULL, 0); if (!error && !git_config_find_system(&buf)) error = git_config_add_file_ondisk(cfg, buf.ptr, GIT_CONFIG_LEVEL_SYSTEM, NULL, 0); if (!error && !git_config_find_programdata(&buf)) error = git_config_add_file_ondisk(cfg, buf.ptr, GIT_CONFIG_LEVEL_PROGRAMDATA, NULL, 0); git_buf_dispose(&buf); if (error) { git_config_free(cfg); cfg = NULL; } *out = cfg; return error; } int git_config_lock(git_transaction **out, git_config *cfg) { int error; git_config_backend *backend; backend_internal *internal; GIT_ASSERT_ARG(cfg); internal = git_vector_get(&cfg->backends, 0); if (!internal || !internal->backend) { git_error_set(GIT_ERROR_CONFIG, "cannot lock; the config has no backends"); return -1; } backend = internal->backend; if ((error = backend->lock(backend)) < 0) return error; return git_transaction_config_new(out, cfg); } int git_config_unlock(git_config *cfg, int commit) { git_config_backend *backend; backend_internal *internal; GIT_ASSERT_ARG(cfg); internal = git_vector_get(&cfg->backends, 0); if (!internal || !internal->backend) { git_error_set(GIT_ERROR_CONFIG, "cannot lock; the config has no backends"); return -1; } backend = internal->backend; return backend->unlock(backend, commit); } /*********** * Parsers ***********/ int git_config_lookup_map_value( int *out, const git_configmap *maps, size_t map_n, const char *value) { size_t i; for (i = 0; i < map_n; ++i) { const git_configmap *m = maps + i; switch (m->type) { case GIT_CONFIGMAP_FALSE: case GIT_CONFIGMAP_TRUE: { int bool_val; if (git_config_parse_bool(&bool_val, value) == 0 && bool_val == (int)m->type) { *out = m->map_value; return 0; } break; } case GIT_CONFIGMAP_INT32: if (git_config_parse_int32(out, value) == 0) return 0; break; case GIT_CONFIGMAP_STRING: if (value && strcasecmp(value, m->str_match) == 0) { *out = m->map_value; return 0; } break; } } git_error_set(GIT_ERROR_CONFIG, "failed to map '%s'", value); return -1; } int git_config_lookup_map_enum(git_configmap_t *type_out, const char **str_out, const git_configmap *maps, size_t map_n, int enum_val) { size_t i; for (i = 0; i < map_n; i++) { const git_configmap *m = &maps[i]; if (m->map_value != enum_val) continue; *type_out = m->type; *str_out = m->str_match; return 0; } git_error_set(GIT_ERROR_CONFIG, "invalid enum value"); return GIT_ENOTFOUND; } int git_config_parse_bool(int *out, const char *value) { if (git__parse_bool(out, value) == 0) return 0; if (git_config_parse_int32(out, value) == 0) { *out = !!(*out); return 0; } git_error_set(GIT_ERROR_CONFIG, "failed to parse '%s' as a boolean value", value); return -1; } int git_config_parse_int64(int64_t *out, const char *value) { const char *num_end; int64_t num; if (!value || git__strntol64(&num, value, strlen(value), &num_end, 0) < 0) goto fail_parse; switch (*num_end) { case 'g': case 'G': num *= 1024; /* fallthrough */ case 'm': case 'M': num *= 1024; /* fallthrough */ case 'k': case 'K': num *= 1024; /* check that that there are no more characters after the * given modifier suffix */ if (num_end[1] != '\0') return -1; /* fallthrough */ case '\0': *out = num; return 0; default: goto fail_parse; } fail_parse: git_error_set(GIT_ERROR_CONFIG, "failed to parse '%s' as an integer", value ? value : "(null)"); return -1; } int git_config_parse_int32(int32_t *out, const char *value) { int64_t tmp; int32_t truncate; if (git_config_parse_int64(&tmp, value) < 0) goto fail_parse; truncate = tmp & 0xFFFFFFFF; if (truncate != tmp) goto fail_parse; *out = truncate; return 0; fail_parse: git_error_set(GIT_ERROR_CONFIG, "failed to parse '%s' as a 32-bit integer", value ? value : "(null)"); return -1; } int git_config_parse_path(git_buf *out, const char *value) { int error; GIT_ASSERT_ARG(out); GIT_ASSERT_ARG(value); if ((error = git_buf_sanitize(out)) < 0) return error; if (value[0] == '~') { if (value[1] != '\0' && value[1] != '/') { git_error_set(GIT_ERROR_CONFIG, "retrieving a homedir by name is not supported"); return -1; } return git_sysdir_expand_global_file(out, value[1] ? &value[2] : NULL); } return git_buf_sets(out, value); } static int normalize_section(char *start, char *end) { char *scan; if (start == end) return GIT_EINVALIDSPEC; /* Validate and downcase range */ for (scan = start; *scan; ++scan) { if (end && scan >= end) break; if (isalnum(*scan)) *scan = (char)git__tolower(*scan); else if (*scan != '-' || scan == start) return GIT_EINVALIDSPEC; } if (scan == start) return GIT_EINVALIDSPEC; return 0; } /* Take something the user gave us and make it nice for our hash function */ int git_config__normalize_name(const char *in, char **out) { char *name, *fdot, *ldot; GIT_ASSERT_ARG(in); GIT_ASSERT_ARG(out); name = git__strdup(in); GIT_ERROR_CHECK_ALLOC(name); fdot = strchr(name, '.'); ldot = strrchr(name, '.'); if (fdot == NULL || fdot == name || ldot == NULL || !ldot[1]) goto invalid; /* Validate and downcase up to first dot and after last dot */ if (normalize_section(name, fdot) < 0 || normalize_section(ldot + 1, NULL) < 0) goto invalid; /* If there is a middle range, make sure it doesn't have newlines */ while (fdot < ldot) if (*fdot++ == '\n') goto invalid; *out = name; return 0; invalid: git__free(name); git_error_set(GIT_ERROR_CONFIG, "invalid config item name '%s'", in); return GIT_EINVALIDSPEC; } struct rename_data { git_config *config; git_buf *name; size_t old_len; }; static int rename_config_entries_cb( const git_config_entry *entry, void *payload) { int error = 0; struct rename_data *data = (struct rename_data *)payload; size_t base_len = git_buf_len(data->name); if (base_len > 0 && !(error = git_buf_puts(data->name, entry->name + data->old_len))) { error = git_config_set_string( data->config, git_buf_cstr(data->name), entry->value); git_buf_truncate(data->name, base_len); } if (!error) error = git_config_delete_entry(data->config, entry->name); return error; } int git_config_rename_section( git_repository *repo, const char *old_section_name, const char *new_section_name) { git_config *config; git_buf pattern = GIT_BUF_INIT, replace = GIT_BUF_INIT; int error = 0; struct rename_data data; git_buf_puts_escape_regex(&pattern, old_section_name); if ((error = git_buf_puts(&pattern, "\\..+")) < 0) goto cleanup; if ((error = git_repository_config__weakptr(&config, repo)) < 0) goto cleanup; data.config = config; data.name = &replace; data.old_len = strlen(old_section_name) + 1; if ((error = git_buf_join(&replace, '.', new_section_name, "")) < 0) goto cleanup; if (new_section_name != NULL && (error = normalize_section(replace.ptr, strchr(replace.ptr, '.'))) < 0) { git_error_set( GIT_ERROR_CONFIG, "invalid config section '%s'", new_section_name); goto cleanup; } error = git_config_foreach_match( config, git_buf_cstr(&pattern), rename_config_entries_cb, &data); cleanup: git_buf_dispose(&pattern); git_buf_dispose(&replace); return error; } int git_config_init_backend(git_config_backend *backend, unsigned int version) { GIT_INIT_STRUCTURE_FROM_TEMPLATE( backend, version, git_config_backend, GIT_CONFIG_BACKEND_INIT); return 0; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/unix/posix.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_unix_posix_h__ #define INCLUDE_unix_posix_h__ #ifndef LIBGIT2_NO_FEATURES_H # include "git2/sys/features.h" #endif #include <stdio.h> #include <dirent.h> #include <sys/param.h> #include <sys/time.h> #include <sys/stat.h> typedef int GIT_SOCKET; #define INVALID_SOCKET -1 #define p_lseek(f,n,w) lseek(f, n, w) #define p_fstat(f,b) fstat(f, b) #define p_lstat(p,b) lstat(p,b) #define p_stat(p,b) stat(p, b) #if defined(GIT_USE_STAT_MTIMESPEC) # define st_atime_nsec st_atimespec.tv_nsec # define st_mtime_nsec st_mtimespec.tv_nsec # define st_ctime_nsec st_ctimespec.tv_nsec #elif defined(GIT_USE_STAT_MTIM) # define st_atime_nsec st_atim.tv_nsec # define st_mtime_nsec st_mtim.tv_nsec # define st_ctime_nsec st_ctim.tv_nsec #elif !defined(GIT_USE_STAT_MTIME_NSEC) && defined(GIT_USE_NSEC) # error GIT_USE_NSEC defined but unknown struct stat nanosecond type #endif #define p_utimes(f, t) utimes(f, t) #define p_readlink(a, b, c) readlink(a, b, c) #define p_symlink(o,n) symlink(o, n) #define p_link(o,n) link(o, n) #define p_unlink(p) unlink(p) #define p_mkdir(p,m) mkdir(p, m) extern char *p_realpath(const char *, char *); GIT_INLINE(int) p_fsync(int fd) { p_fsync__cnt++; return fsync(fd); } #define p_recv(s,b,l,f) recv(s,b,l,f) #define p_send(s,b,l,f) send(s,b,l,f) #define p_inet_pton(a, b, c) inet_pton(a, b, c) #define p_strcasecmp(s1, s2) strcasecmp(s1, s2) #define p_strncasecmp(s1, s2, c) strncasecmp(s1, s2, c) #define p_vsnprintf(b, c, f, a) vsnprintf(b, c, f, a) #define p_snprintf snprintf #define p_mkstemp(p) mkstemp(p) #define p_chdir(p) chdir(p) #define p_rmdir(p) rmdir(p) #define p_access(p,m) access(p,m) #define p_ftruncate(fd, sz) ftruncate(fd, sz) /* * Pre-Android 5 did not implement a virtual filesystem atop FAT * partitions for Unix permissions, which causes chmod to fail. However, * Unix permissions have no effect on Android anyway as file permissions * are not actually managed this way, so treating it as a no-op across * all Android is safe. */ #ifdef __ANDROID__ # define p_chmod(p,m) 0 #else # define p_chmod(p,m) chmod(p, m) #endif /* see win32/posix.h for explanation about why this exists */ #define p_lstat_posixly(p,b) lstat(p,b) #define p_localtime_r(c, r) localtime_r(c, r) #define p_gmtime_r(c, r) gmtime_r(c, r) #define p_timeval timeval #ifdef GIT_USE_FUTIMENS GIT_INLINE(int) p_futimes(int f, const struct p_timeval t[2]) { struct timespec s[2]; s[0].tv_sec = t[0].tv_sec; s[0].tv_nsec = t[0].tv_usec * 1000; s[1].tv_sec = t[1].tv_sec; s[1].tv_nsec = t[1].tv_usec * 1000; return futimens(f, s); } #else # define p_futimes futimes #endif #define p_pread(f, d, s, o) pread(f, d, s, o) #define p_pwrite(f, d, s, o) pwrite(f, d, s, o) #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/unix/realpath.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "common.h" #include "git2/common.h" #ifndef GIT_WIN32 #include <limits.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> char *p_realpath(const char *pathname, char *resolved) { char *ret; if ((ret = realpath(pathname, resolved)) == NULL) return NULL; #ifdef __OpenBSD__ /* The OpenBSD realpath function behaves differently, * figure out if the file exists */ if (access(ret, F_OK) < 0) ret = NULL; #endif return ret; } #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/unix/map.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "common.h" #include "git2/common.h" #if !defined(GIT_WIN32) && !defined(NO_MMAP) #include "map.h" #include <sys/mman.h> #include <unistd.h> #include <errno.h> int git__page_size(size_t *page_size) { long sc_page_size = sysconf(_SC_PAGE_SIZE); if (sc_page_size < 0) { git_error_set(GIT_ERROR_OS, "can't determine system page size"); return -1; } *page_size = (size_t) sc_page_size; return 0; } int git__mmap_alignment(size_t *alignment) { return git__page_size(alignment); } int p_mmap(git_map *out, size_t len, int prot, int flags, int fd, off64_t offset) { int mprot = PROT_READ; int mflag = 0; GIT_MMAP_VALIDATE(out, len, prot, flags); out->data = NULL; out->len = 0; if (prot & GIT_PROT_WRITE) mprot |= PROT_WRITE; if ((flags & GIT_MAP_TYPE) == GIT_MAP_SHARED) mflag = MAP_SHARED; else if ((flags & GIT_MAP_TYPE) == GIT_MAP_PRIVATE) mflag = MAP_PRIVATE; else mflag = MAP_SHARED; out->data = mmap(NULL, len, mprot, mflag, fd, offset); if (!out->data || out->data == MAP_FAILED) { git_error_set(GIT_ERROR_OS, "failed to mmap. Could not write data"); return -1; } out->len = len; return 0; } int p_munmap(git_map *map) { GIT_ASSERT_ARG(map); munmap(map->data, map->len); map->data = NULL; map->len = 0; return 0; } #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/unix/pthread.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_unix_pthread_h__ #define INCLUDE_unix_pthread_h__ typedef struct { pthread_t thread; } git_thread; GIT_INLINE(int) git_threads_global_init(void) { return 0; } #define git_thread_create(git_thread_ptr, start_routine, arg) \ pthread_create(&(git_thread_ptr)->thread, NULL, start_routine, arg) #define git_thread_join(git_thread_ptr, status) \ pthread_join((git_thread_ptr)->thread, status) #define git_thread_currentid() ((size_t)(pthread_self())) #define git_thread_exit(retval) pthread_exit(retval) /* Git Mutex */ #define git_mutex pthread_mutex_t #define git_mutex_init(a) pthread_mutex_init(a, NULL) #define git_mutex_lock(a) pthread_mutex_lock(a) #define git_mutex_unlock(a) pthread_mutex_unlock(a) #define git_mutex_free(a) pthread_mutex_destroy(a) /* Git condition vars */ #define git_cond pthread_cond_t #define git_cond_init(c) pthread_cond_init(c, NULL) #define git_cond_free(c) pthread_cond_destroy(c) #define git_cond_wait(c, l) pthread_cond_wait(c, l) #define git_cond_signal(c) pthread_cond_signal(c) #define git_cond_broadcast(c) pthread_cond_broadcast(c) /* Pthread (-ish) rwlock * * This differs from normal pthreads rwlocks in two ways: * 1. Separate APIs for releasing read locks and write locks (as * opposed to the pure POSIX API which only has one unlock fn) * 2. You should not use recursive read locks (i.e. grabbing a read * lock in a thread that already holds a read lock) because the * Windows implementation doesn't support it */ #define git_rwlock pthread_rwlock_t #define git_rwlock_init(a) pthread_rwlock_init(a, NULL) #define git_rwlock_rdlock(a) pthread_rwlock_rdlock(a) #define git_rwlock_rdunlock(a) pthread_rwlock_unlock(a) #define git_rwlock_wrlock(a) pthread_rwlock_wrlock(a) #define git_rwlock_wrunlock(a) pthread_rwlock_unlock(a) #define git_rwlock_free(a) pthread_rwlock_destroy(a) #define GIT_RWLOCK_STATIC_INIT PTHREAD_RWLOCK_INITIALIZER #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/xdiff/xmacros.h
/* * LibXDiff by Davide Libenzi ( File Differential Library ) * Copyright (C) 2003 Davide Libenzi * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see * <http://www.gnu.org/licenses/>. * * Davide Libenzi <[email protected]> * */ #if !defined(XMACROS_H) #define XMACROS_H #define XDL_MIN(a, b) ((a) < (b) ? (a): (b)) #define XDL_MAX(a, b) ((a) > (b) ? (a): (b)) #define XDL_ABS(v) ((v) >= 0 ? (v): -(v)) #define XDL_ISDIGIT(c) ((c) >= '0' && (c) <= '9') #define XDL_ISSPACE(c) (isspace((unsigned char)(c))) #define XDL_ADDBITS(v,b) ((v) + ((v) >> (b))) #define XDL_MASKBITS(b) ((1UL << (b)) - 1) #define XDL_HASHLONG(v,b) (XDL_ADDBITS((unsigned long)(v), b) & XDL_MASKBITS(b)) #define XDL_PTRFREE(p) do { if (p) { xdl_free(p); (p) = NULL; } } while (0) #define XDL_LE32_PUT(p, v) \ do { \ unsigned char *__p = (unsigned char *) (p); \ *__p++ = (unsigned char) (v); \ *__p++ = (unsigned char) ((v) >> 8); \ *__p++ = (unsigned char) ((v) >> 16); \ *__p = (unsigned char) ((v) >> 24); \ } while (0) #define XDL_LE32_GET(p, v) \ do { \ unsigned char const *__p = (unsigned char const *) (p); \ (v) = (unsigned long) __p[0] | ((unsigned long) __p[1]) << 8 | \ ((unsigned long) __p[2]) << 16 | ((unsigned long) __p[3]) << 24; \ } while (0) #endif /* #if !defined(XMACROS_H) */
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/xdiff/xtypes.h
/* * LibXDiff by Davide Libenzi ( File Differential Library ) * Copyright (C) 2003 Davide Libenzi * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see * <http://www.gnu.org/licenses/>. * * Davide Libenzi <[email protected]> * */ #if !defined(XTYPES_H) #define XTYPES_H typedef struct s_chanode { struct s_chanode *next; long icurr; } chanode_t; typedef struct s_chastore { chanode_t *head, *tail; long isize, nsize; chanode_t *ancur; chanode_t *sncur; long scurr; } chastore_t; typedef struct s_xrecord { struct s_xrecord *next; char const *ptr; long size; unsigned long ha; } xrecord_t; typedef struct s_xdfile { chastore_t rcha; long nrec; unsigned int hbits; xrecord_t **rhash; long dstart, dend; xrecord_t **recs; char *rchg; long *rindex; long nreff; unsigned long *ha; } xdfile_t; typedef struct s_xdfenv { xdfile_t xdf1, xdf2; } xdfenv_t; #endif /* #if !defined(XTYPES_H) */
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/xdiff/xprepare.h
/* * LibXDiff by Davide Libenzi ( File Differential Library ) * Copyright (C) 2003 Davide Libenzi * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see * <http://www.gnu.org/licenses/>. * * Davide Libenzi <[email protected]> * */ #if !defined(XPREPARE_H) #define XPREPARE_H int xdl_prepare_env(mmfile_t *mf1, mmfile_t *mf2, xpparam_t const *xpp, xdfenv_t *xe); void xdl_free_env(xdfenv_t *xe); #endif /* #if !defined(XPREPARE_H) */
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/xdiff/xmerge.c
/* * LibXDiff by Davide Libenzi ( File Differential Library ) * Copyright (C) 2003-2006 Davide Libenzi, Johannes E. Schindelin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see * <http://www.gnu.org/licenses/>. * * Davide Libenzi <[email protected]> * */ #include "xinclude.h" typedef struct s_xdmerge { struct s_xdmerge *next; /* * 0 = conflict, * 1 = no conflict, take first, * 2 = no conflict, take second. * 3 = no conflict, take both. */ int mode; /* * These point at the respective postimages. E.g. <i1,chg1> is * how side #1 wants to change the common ancestor; if there is no * overlap, lines before i1 in the postimage of side #1 appear * in the merge result as a region touched by neither side. */ long i1, i2; long chg1, chg2; /* * These point at the preimage; of course there is just one * preimage, that is from the shared common ancestor. */ long i0; long chg0; } xdmerge_t; static int xdl_append_merge(xdmerge_t **merge, int mode, long i0, long chg0, long i1, long chg1, long i2, long chg2) { xdmerge_t *m = *merge; if (m && (i1 <= m->i1 + m->chg1 || i2 <= m->i2 + m->chg2)) { if (mode != m->mode) m->mode = 0; m->chg0 = i0 + chg0 - m->i0; m->chg1 = i1 + chg1 - m->i1; m->chg2 = i2 + chg2 - m->i2; } else { m = xdl_malloc(sizeof(xdmerge_t)); if (!m) return -1; m->next = NULL; m->mode = mode; m->i0 = i0; m->chg0 = chg0; m->i1 = i1; m->chg1 = chg1; m->i2 = i2; m->chg2 = chg2; if (*merge) (*merge)->next = m; *merge = m; } return 0; } static int xdl_cleanup_merge(xdmerge_t *c) { int count = 0; xdmerge_t *next_c; /* were there conflicts? */ for (; c; c = next_c) { if (c->mode == 0) count++; next_c = c->next; free(c); } return count; } static int xdl_merge_cmp_lines(xdfenv_t *xe1, int i1, xdfenv_t *xe2, int i2, int line_count, long flags) { int i; xrecord_t **rec1 = xe1->xdf2.recs + i1; xrecord_t **rec2 = xe2->xdf2.recs + i2; for (i = 0; i < line_count; i++) { int result = xdl_recmatch(rec1[i]->ptr, rec1[i]->size, rec2[i]->ptr, rec2[i]->size, flags); if (!result) return -1; } return 0; } static int xdl_recs_copy_0(size_t *out, int use_orig, xdfenv_t *xe, int i, int count, int needs_cr, int add_nl, char *dest) { xrecord_t **recs; size_t size = 0; *out = 0; recs = (use_orig ? xe->xdf1.recs : xe->xdf2.recs) + i; if (count < 1) return 0; for (i = 0; i < count; ) { if (dest) memcpy(dest + size, recs[i]->ptr, recs[i]->size); GIT_ERROR_CHECK_ALLOC_ADD(&size, size, recs[i++]->size); } if (add_nl) { i = recs[count - 1]->size; if (i == 0 || recs[count - 1]->ptr[i - 1] != '\n') { if (needs_cr) { if (dest) dest[size] = '\r'; GIT_ERROR_CHECK_ALLOC_ADD(&size, size, 1); } if (dest) dest[size] = '\n'; GIT_ERROR_CHECK_ALLOC_ADD(&size, size, 1); } } *out = size; return 0; } static int xdl_recs_copy(size_t *out, xdfenv_t *xe, int i, int count, int needs_cr, int add_nl, char *dest) { return xdl_recs_copy_0(out, 0, xe, i, count, needs_cr, add_nl, dest); } static int xdl_orig_copy(size_t *out, xdfenv_t *xe, int i, int count, int needs_cr, int add_nl, char *dest) { return xdl_recs_copy_0(out, 1, xe, i, count, needs_cr, add_nl, dest); } /* * Returns 1 if the i'th line ends in CR/LF (if it is the last line and * has no eol, the preceding line, if any), 0 if it ends in LF-only, and * -1 if the line ending cannot be determined. */ static int is_eol_crlf(xdfile_t *file, int i) { long size; if (i < file->nrec - 1) /* All lines before the last *must* end in LF */ return (size = file->recs[i]->size) > 1 && file->recs[i]->ptr[size - 2] == '\r'; if (!file->nrec) /* Cannot determine eol style from empty file */ return -1; if ((size = file->recs[i]->size) && file->recs[i]->ptr[size - 1] == '\n') /* Last line; ends in LF; Is it CR/LF? */ return size > 1 && file->recs[i]->ptr[size - 2] == '\r'; if (!i) /* The only line has no eol */ return -1; /* Determine eol from second-to-last line */ return (size = file->recs[i - 1]->size) > 1 && file->recs[i - 1]->ptr[size - 2] == '\r'; } static int is_cr_needed(xdfenv_t *xe1, xdfenv_t *xe2, xdmerge_t *m) { int needs_cr; /* Match post-images' preceding, or first, lines' end-of-line style */ needs_cr = is_eol_crlf(&xe1->xdf2, m->i1 ? m->i1 - 1 : 0); if (needs_cr) needs_cr = is_eol_crlf(&xe2->xdf2, m->i2 ? m->i2 - 1 : 0); /* Look at pre-image's first line, unless we already settled on LF */ if (needs_cr) needs_cr = is_eol_crlf(&xe1->xdf1, 0); /* If still undecided, use LF-only */ return needs_cr < 0 ? 0 : needs_cr; } static int fill_conflict_hunk(size_t *out, xdfenv_t *xe1, const char *name1, xdfenv_t *xe2, const char *name2, const char *name3, size_t size, int i, int style, xdmerge_t *m, char *dest, int marker_size) { int marker1_size = (name1 ? (int)strlen(name1) + 1 : 0); int marker2_size = (name2 ? (int)strlen(name2) + 1 : 0); int marker3_size = (name3 ? (int)strlen(name3) + 1 : 0); int needs_cr = is_cr_needed(xe1, xe2, m); size_t copied; *out = 0; if (marker_size <= 0) marker_size = DEFAULT_CONFLICT_MARKER_SIZE; /* Before conflicting part */ if (xdl_recs_copy(&copied, xe1, i, m->i1 - i, 0, 0, dest ? dest + size : NULL) < 0) return -1; GIT_ERROR_CHECK_ALLOC_ADD(&size, size, copied); if (!dest) { GIT_ERROR_CHECK_ALLOC_ADD5(&size, size, marker_size, 1, needs_cr, marker1_size); } else { memset(dest + size, '<', marker_size); size += marker_size; if (marker1_size) { dest[size] = ' '; memcpy(dest + size + 1, name1, marker1_size - 1); size += marker1_size; } if (needs_cr) dest[size++] = '\r'; dest[size++] = '\n'; } /* Postimage from side #1 */ if (xdl_recs_copy(&copied, xe1, m->i1, m->chg1, needs_cr, 1, dest ? dest + size : NULL) < 0) return -1; GIT_ERROR_CHECK_ALLOC_ADD(&size, size, copied); if (style == XDL_MERGE_DIFF3) { /* Shared preimage */ if (!dest) { GIT_ERROR_CHECK_ALLOC_ADD5(&size, size, marker_size, 1, needs_cr, marker3_size); } else { memset(dest + size, '|', marker_size); size += marker_size; if (marker3_size) { dest[size] = ' '; memcpy(dest + size + 1, name3, marker3_size - 1); size += marker3_size; } if (needs_cr) dest[size++] = '\r'; dest[size++] = '\n'; } if (xdl_orig_copy(&copied, xe1, m->i0, m->chg0, needs_cr, 1, dest ? dest + size : NULL) < 0) return -1; GIT_ERROR_CHECK_ALLOC_ADD(&size, size, copied); } if (!dest) { GIT_ERROR_CHECK_ALLOC_ADD4(&size, size, marker_size, 1, needs_cr); } else { memset(dest + size, '=', marker_size); size += marker_size; if (needs_cr) dest[size++] = '\r'; dest[size++] = '\n'; } /* Postimage from side #2 */ if (xdl_recs_copy(&copied, xe2, m->i2, m->chg2, needs_cr, 1, dest ? dest + size : NULL) < 0) return -1; GIT_ERROR_CHECK_ALLOC_ADD(&size, size, copied); if (!dest) { GIT_ERROR_CHECK_ALLOC_ADD5(&size, size, marker_size, 1, needs_cr, marker2_size); } else { memset(dest + size, '>', marker_size); size += marker_size; if (marker2_size) { dest[size] = ' '; memcpy(dest + size + 1, name2, marker2_size - 1); size += marker2_size; } if (needs_cr) dest[size++] = '\r'; dest[size++] = '\n'; } *out = size; return 0; } static int xdl_fill_merge_buffer(size_t *out, xdfenv_t *xe1, const char *name1, xdfenv_t *xe2, const char *name2, const char *ancestor_name, int favor, xdmerge_t *m, char *dest, int style, int marker_size) { size_t size, copied; int i; *out = 0; for (size = i = 0; m; m = m->next) { if (favor && !m->mode) m->mode = favor; if (m->mode == 0) { if (fill_conflict_hunk(&size, xe1, name1, xe2, name2, ancestor_name, size, i, style, m, dest, marker_size) < 0) return -1; } else if (m->mode & 3) { /* Before conflicting part */ if (xdl_recs_copy(&copied, xe1, i, m->i1 - i, 0, 0, dest ? dest + size : NULL) < 0) return -1; GIT_ERROR_CHECK_ALLOC_ADD(&size, size, copied); /* Postimage from side #1 */ if (m->mode & 1) { int needs_cr = is_cr_needed(xe1, xe2, m); if (xdl_recs_copy(&copied, xe1, m->i1, m->chg1, needs_cr, (m->mode & 2), dest ? dest + size : NULL) < 0) return -1; GIT_ERROR_CHECK_ALLOC_ADD(&size, size, copied); } /* Postimage from side #2 */ if (m->mode & 2) { if (xdl_recs_copy(&copied, xe2, m->i2, m->chg2, 0, 0, dest ? dest + size : NULL) < 0) return -1; GIT_ERROR_CHECK_ALLOC_ADD(&size, size, copied); } } else continue; i = m->i1 + m->chg1; } if (xdl_recs_copy(&copied, xe1, i, xe1->xdf2.nrec - i, 0, 0, dest ? dest + size : NULL) < 0) return -1; GIT_ERROR_CHECK_ALLOC_ADD(&size, size, copied); *out = size; return 0; } /* * Sometimes, changes are not quite identical, but differ in only a few * lines. Try hard to show only these few lines as conflicting. */ static int xdl_refine_conflicts(xdfenv_t *xe1, xdfenv_t *xe2, xdmerge_t *m, xpparam_t const *xpp) { for (; m; m = m->next) { mmfile_t t1, t2; xdfenv_t xe; xdchange_t *xscr, *x; int i1 = m->i1, i2 = m->i2; /* let's handle just the conflicts */ if (m->mode) continue; /* no sense refining a conflict when one side is empty */ if (m->chg1 == 0 || m->chg2 == 0) continue; /* * This probably does not work outside git, since * we have a very simple mmfile structure. */ t1.ptr = (char *)xe1->xdf2.recs[m->i1]->ptr; t1.size = xe1->xdf2.recs[m->i1 + m->chg1 - 1]->ptr + xe1->xdf2.recs[m->i1 + m->chg1 - 1]->size - t1.ptr; t2.ptr = (char *)xe2->xdf2.recs[m->i2]->ptr; t2.size = xe2->xdf2.recs[m->i2 + m->chg2 - 1]->ptr + xe2->xdf2.recs[m->i2 + m->chg2 - 1]->size - t2.ptr; if (xdl_do_diff(&t1, &t2, xpp, &xe) < 0) return -1; if (xdl_change_compact(&xe.xdf1, &xe.xdf2, xpp->flags) < 0 || xdl_change_compact(&xe.xdf2, &xe.xdf1, xpp->flags) < 0 || xdl_build_script(&xe, &xscr) < 0) { xdl_free_env(&xe); return -1; } if (!xscr) { /* If this happens, the changes are identical. */ xdl_free_env(&xe); m->mode = 4; continue; } x = xscr; m->i1 = xscr->i1 + i1; m->chg1 = xscr->chg1; m->i2 = xscr->i2 + i2; m->chg2 = xscr->chg2; while (xscr->next) { xdmerge_t *m2 = xdl_malloc(sizeof(xdmerge_t)); if (!m2) { xdl_free_env(&xe); xdl_free_script(x); return -1; } xscr = xscr->next; m2->next = m->next; m->next = m2; m = m2; m->mode = 0; m->i1 = xscr->i1 + i1; m->chg1 = xscr->chg1; m->i2 = xscr->i2 + i2; m->chg2 = xscr->chg2; } xdl_free_env(&xe); xdl_free_script(x); } return 0; } static int line_contains_alnum(const char *ptr, long size) { while (size--) if (isalnum((unsigned char)*(ptr++))) return 1; return 0; } static int lines_contain_alnum(xdfenv_t *xe, int i, int chg) { for (; chg; chg--, i++) if (line_contains_alnum(xe->xdf2.recs[i]->ptr, xe->xdf2.recs[i]->size)) return 1; return 0; } /* * This function merges m and m->next, marking everything between those hunks * as conflicting, too. */ static void xdl_merge_two_conflicts(xdmerge_t *m) { xdmerge_t *next_m = m->next; m->chg1 = next_m->i1 + next_m->chg1 - m->i1; m->chg2 = next_m->i2 + next_m->chg2 - m->i2; m->next = next_m->next; free(next_m); } /* * If there are less than 3 non-conflicting lines between conflicts, * it appears simpler -- because it takes up less (or as many) lines -- * if the lines are moved into the conflicts. */ static int xdl_simplify_non_conflicts(xdfenv_t *xe1, xdmerge_t *m, int simplify_if_no_alnum) { int result = 0; if (!m) return result; for (;;) { xdmerge_t *next_m = m->next; int begin, end; if (!next_m) return result; begin = m->i1 + m->chg1; end = next_m->i1; if (m->mode != 0 || next_m->mode != 0 || (end - begin > 3 && (!simplify_if_no_alnum || lines_contain_alnum(xe1, begin, end - begin)))) { m = next_m; } else { result++; xdl_merge_two_conflicts(m); } } } /* * level == 0: mark all overlapping changes as conflict * level == 1: mark overlapping changes as conflict only if not identical * level == 2: analyze non-identical changes for minimal conflict set * level == 3: analyze non-identical changes for minimal conflict set, but * treat hunks not containing any letter or number as conflicting * * returns < 0 on error, == 0 for no conflicts, else number of conflicts */ static int xdl_do_merge(xdfenv_t *xe1, xdchange_t *xscr1, xdfenv_t *xe2, xdchange_t *xscr2, xmparam_t const *xmp, mmbuffer_t *result) { xdmerge_t *changes, *c; xpparam_t const *xpp = &xmp->xpp; const char *const ancestor_name = xmp->ancestor; const char *const name1 = xmp->file1; const char *const name2 = xmp->file2; int i0, i1, i2, chg0, chg1, chg2; int level = xmp->level; int style = xmp->style; int favor = xmp->favor; if (style == XDL_MERGE_DIFF3) { /* * "diff3 -m" output does not make sense for anything * more aggressive than XDL_MERGE_EAGER. */ if (XDL_MERGE_EAGER < level) level = XDL_MERGE_EAGER; } c = changes = NULL; while (xscr1 && xscr2) { if (!changes) changes = c; if (xscr1->i1 + xscr1->chg1 < xscr2->i1) { i0 = xscr1->i1; i1 = xscr1->i2; i2 = xscr2->i2 - xscr2->i1 + xscr1->i1; chg0 = xscr1->chg1; chg1 = xscr1->chg2; chg2 = xscr1->chg1; if (xdl_append_merge(&c, 1, i0, chg0, i1, chg1, i2, chg2)) { xdl_cleanup_merge(changes); return -1; } xscr1 = xscr1->next; continue; } if (xscr2->i1 + xscr2->chg1 < xscr1->i1) { i0 = xscr2->i1; i1 = xscr1->i2 - xscr1->i1 + xscr2->i1; i2 = xscr2->i2; chg0 = xscr2->chg1; chg1 = xscr2->chg1; chg2 = xscr2->chg2; if (xdl_append_merge(&c, 2, i0, chg0, i1, chg1, i2, chg2)) { xdl_cleanup_merge(changes); return -1; } xscr2 = xscr2->next; continue; } if (level == XDL_MERGE_MINIMAL || xscr1->i1 != xscr2->i1 || xscr1->chg1 != xscr2->chg1 || xscr1->chg2 != xscr2->chg2 || xdl_merge_cmp_lines(xe1, xscr1->i2, xe2, xscr2->i2, xscr1->chg2, xpp->flags)) { /* conflict */ int off = xscr1->i1 - xscr2->i1; int ffo = off + xscr1->chg1 - xscr2->chg1; i0 = xscr1->i1; i1 = xscr1->i2; i2 = xscr2->i2; if (off > 0) { i0 -= off; i1 -= off; } else i2 += off; chg0 = xscr1->i1 + xscr1->chg1 - i0; chg1 = xscr1->i2 + xscr1->chg2 - i1; chg2 = xscr2->i2 + xscr2->chg2 - i2; if (ffo < 0) { chg0 -= ffo; chg1 -= ffo; } else chg2 += ffo; if (xdl_append_merge(&c, 0, i0, chg0, i1, chg1, i2, chg2)) { xdl_cleanup_merge(changes); return -1; } } i1 = xscr1->i1 + xscr1->chg1; i2 = xscr2->i1 + xscr2->chg1; if (i1 >= i2) xscr2 = xscr2->next; if (i2 >= i1) xscr1 = xscr1->next; } while (xscr1) { if (!changes) changes = c; i0 = xscr1->i1; i1 = xscr1->i2; i2 = xscr1->i1 + xe2->xdf2.nrec - xe2->xdf1.nrec; chg0 = xscr1->chg1; chg1 = xscr1->chg2; chg2 = xscr1->chg1; if (xdl_append_merge(&c, 1, i0, chg0, i1, chg1, i2, chg2)) { xdl_cleanup_merge(changes); return -1; } xscr1 = xscr1->next; } while (xscr2) { if (!changes) changes = c; i0 = xscr2->i1; i1 = xscr2->i1 + xe1->xdf2.nrec - xe1->xdf1.nrec; i2 = xscr2->i2; chg0 = xscr2->chg1; chg1 = xscr2->chg1; chg2 = xscr2->chg2; if (xdl_append_merge(&c, 2, i0, chg0, i1, chg1, i2, chg2)) { xdl_cleanup_merge(changes); return -1; } xscr2 = xscr2->next; } if (!changes) changes = c; /* refine conflicts */ if (XDL_MERGE_ZEALOUS <= level && (xdl_refine_conflicts(xe1, xe2, changes, xpp) < 0 || xdl_simplify_non_conflicts(xe1, changes, XDL_MERGE_ZEALOUS < level) < 0)) { xdl_cleanup_merge(changes); return -1; } /* output */ if (result) { int marker_size = xmp->marker_size; size_t size; if (xdl_fill_merge_buffer(&size, xe1, name1, xe2, name2, ancestor_name, favor, changes, NULL, style, marker_size) < 0) return -1; result->ptr = xdl_malloc(size); if (!result->ptr) { xdl_cleanup_merge(changes); return -1; } result->size = size; if (xdl_fill_merge_buffer(&size, xe1, name1, xe2, name2, ancestor_name, favor, changes, result->ptr, style, marker_size) < 0) return -1; } return xdl_cleanup_merge(changes); } int xdl_merge(mmfile_t *orig, mmfile_t *mf1, mmfile_t *mf2, xmparam_t const *xmp, mmbuffer_t *result) { xdchange_t *xscr1, *xscr2; xdfenv_t xe1, xe2; int status; xpparam_t const *xpp = &xmp->xpp; result->ptr = NULL; result->size = 0; if (xdl_do_diff(orig, mf1, xpp, &xe1) < 0) { return -1; } if (xdl_do_diff(orig, mf2, xpp, &xe2) < 0) { xdl_free_env(&xe1); return -1; } if (xdl_change_compact(&xe1.xdf1, &xe1.xdf2, xpp->flags) < 0 || xdl_change_compact(&xe1.xdf2, &xe1.xdf1, xpp->flags) < 0 || xdl_build_script(&xe1, &xscr1) < 0) { xdl_free_env(&xe1); return -1; } if (xdl_change_compact(&xe2.xdf1, &xe2.xdf2, xpp->flags) < 0 || xdl_change_compact(&xe2.xdf2, &xe2.xdf1, xpp->flags) < 0 || xdl_build_script(&xe2, &xscr2) < 0) { xdl_free_script(xscr1); xdl_free_env(&xe1); xdl_free_env(&xe2); return -1; } status = 0; if (!xscr1) { result->ptr = xdl_malloc(mf2->size); if (!result->ptr) { xdl_free_script(xscr2); xdl_free_env(&xe1); xdl_free_env(&xe2); return -1; } memcpy(result->ptr, mf2->ptr, mf2->size); result->size = mf2->size; } else if (!xscr2) { result->ptr = xdl_malloc(mf1->size); if (!result->ptr) { xdl_free_script(xscr1); xdl_free_env(&xe1); xdl_free_env(&xe2); return -1; } memcpy(result->ptr, mf1->ptr, mf1->size); result->size = mf1->size; } else { status = xdl_do_merge(&xe1, xscr1, &xe2, xscr2, xmp, result); } xdl_free_script(xscr1); xdl_free_script(xscr2); xdl_free_env(&xe1); xdl_free_env(&xe2); return status; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/xdiff/xhistogram.c
/* * Copyright (C) 2010, Google Inc. * and other copyright owners as documented in JGit's IP log. * * This program and the accompanying materials are made available * under the terms of the Eclipse Distribution License v1.0 which * accompanies this distribution, is reproduced below, and is * available at http://www.eclipse.org/org/documents/edl-v10.php * * 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 Eclipse Foundation, Inc. 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 OWNER 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 "xinclude.h" #include "xtypes.h" #include "xdiff.h" #define MAX_PTR UINT_MAX #define MAX_CNT UINT_MAX #define LINE_END(n) (line##n + count##n - 1) #define LINE_END_PTR(n) (*line##n + *count##n - 1) struct histindex { struct record { unsigned int ptr, cnt; struct record *next; } **records, /* an occurrence */ **line_map; /* map of line to record chain */ chastore_t rcha; unsigned int *next_ptrs; unsigned int table_bits, records_size, line_map_size; unsigned int max_chain_length, key_shift, ptr_shift; unsigned int cnt, has_common; xdfenv_t *env; xpparam_t const *xpp; }; struct region { unsigned int begin1, end1; unsigned int begin2, end2; }; #define LINE_MAP(i, a) (i->line_map[(a) - i->ptr_shift]) #define NEXT_PTR(index, ptr) \ (index->next_ptrs[(ptr) - index->ptr_shift]) #define CNT(index, ptr) \ ((LINE_MAP(index, ptr))->cnt) #define REC(env, s, l) \ (env->xdf##s.recs[l - 1]) static int cmp_recs(xpparam_t const *xpp, xrecord_t *r1, xrecord_t *r2) { return r1->ha == r2->ha && xdl_recmatch(r1->ptr, r1->size, r2->ptr, r2->size, xpp->flags); } #define CMP_ENV(xpp, env, s1, l1, s2, l2) \ (cmp_recs(xpp, REC(env, s1, l1), REC(env, s2, l2))) #define CMP(i, s1, l1, s2, l2) \ (cmp_recs(i->xpp, REC(i->env, s1, l1), REC(i->env, s2, l2))) #define TABLE_HASH(index, side, line) \ XDL_HASHLONG((REC(index->env, side, line))->ha, index->table_bits) static int scanA(struct histindex *index, unsigned int line1, unsigned int count1) { unsigned int ptr; unsigned int tbl_idx; unsigned int chain_len; struct record **rec_chain, *rec; for (ptr = LINE_END(1); line1 <= ptr; ptr--) { tbl_idx = TABLE_HASH(index, 1, ptr); rec_chain = index->records + tbl_idx; rec = *rec_chain; chain_len = 0; while (rec) { if (CMP(index, 1, rec->ptr, 1, ptr)) { /* * ptr is identical to another element. Insert * it onto the front of the existing element * chain. */ NEXT_PTR(index, ptr) = rec->ptr; rec->ptr = ptr; /* cap rec->cnt at MAX_CNT */ rec->cnt = XDL_MIN(MAX_CNT, rec->cnt + 1); LINE_MAP(index, ptr) = rec; goto continue_scan; } rec = rec->next; chain_len++; } if (chain_len == index->max_chain_length) return -1; /* * This is the first time we have ever seen this particular * element in the sequence. Construct a new chain for it. */ if (!(rec = xdl_cha_alloc(&index->rcha))) return -1; rec->ptr = ptr; rec->cnt = 1; rec->next = *rec_chain; *rec_chain = rec; LINE_MAP(index, ptr) = rec; continue_scan: ; /* no op */ } return 0; } static int try_lcs( struct histindex *index, struct region *lcs, unsigned int b_ptr, unsigned int line1, unsigned int count1, unsigned int line2, unsigned int count2) { unsigned int b_next = b_ptr + 1; struct record *rec = index->records[TABLE_HASH(index, 2, b_ptr)]; unsigned int as, ae, bs, be, np, rc; int should_break; for (; rec; rec = rec->next) { if (rec->cnt > index->cnt) { if (!index->has_common) index->has_common = CMP(index, 1, rec->ptr, 2, b_ptr); continue; } as = rec->ptr; if (!CMP(index, 1, as, 2, b_ptr)) continue; index->has_common = 1; for (;;) { should_break = 0; np = NEXT_PTR(index, as); bs = b_ptr; ae = as; be = bs; rc = rec->cnt; while (line1 < as && line2 < bs && CMP(index, 1, as - 1, 2, bs - 1)) { as--; bs--; if (1 < rc) rc = XDL_MIN(rc, CNT(index, as)); } while (ae < LINE_END(1) && be < LINE_END(2) && CMP(index, 1, ae + 1, 2, be + 1)) { ae++; be++; if (1 < rc) rc = XDL_MIN(rc, CNT(index, ae)); } if (b_next <= be) b_next = be + 1; if (lcs->end1 - lcs->begin1 < ae - as || rc < index->cnt) { lcs->begin1 = as; lcs->begin2 = bs; lcs->end1 = ae; lcs->end2 = be; index->cnt = rc; } if (np == 0) break; while (np <= ae) { np = NEXT_PTR(index, np); if (np == 0) { should_break = 1; break; } } if (should_break) break; as = np; } } return b_next; } static int find_lcs( struct histindex *index, struct region *lcs, unsigned int line1, unsigned int count1, unsigned int line2, unsigned int count2) { unsigned int b_ptr; if (scanA(index, line1, count1)) return -1; index->cnt = index->max_chain_length + 1; for (b_ptr = line2; b_ptr <= LINE_END(2); ) b_ptr = try_lcs(index, lcs, b_ptr, line1, count1, line2, count2); return index->has_common && index->max_chain_length < index->cnt; } static int fall_back_to_classic_diff(struct histindex *index, int line1, int count1, int line2, int count2) { xpparam_t xpp; xpp.flags = index->xpp->flags & ~XDF_DIFF_ALGORITHM_MASK; return xdl_fall_back_diff(index->env, &xpp, line1, count1, line2, count2); } static int histogram_diff( xpparam_t const *xpp, xdfenv_t *env, unsigned int line1, unsigned int count1, unsigned int line2, unsigned int count2) { struct histindex index; struct region lcs; size_t sz; int result = -1; if (count1 <= 0 && count2 <= 0) return 0; if (LINE_END(1) >= MAX_PTR) return -1; if (!count1) { while(count2--) env->xdf2.rchg[line2++ - 1] = 1; return 0; } else if (!count2) { while(count1--) env->xdf1.rchg[line1++ - 1] = 1; return 0; } memset(&index, 0, sizeof(index)); index.env = env; index.xpp = xpp; index.records = NULL; index.line_map = NULL; /* in case of early xdl_cha_free() */ index.rcha.head = NULL; index.table_bits = xdl_hashbits(count1); sz = index.records_size = 1 << index.table_bits; GIT_ERROR_CHECK_ALLOC_MULTIPLY(&sz, sz, sizeof(struct record *)); if (!(index.records = (struct record **) xdl_malloc(sz))) goto cleanup; memset(index.records, 0, sz); sz = index.line_map_size = count1; sz *= sizeof(struct record *); if (!(index.line_map = (struct record **) xdl_malloc(sz))) goto cleanup; memset(index.line_map, 0, sz); sz = index.line_map_size; sz *= sizeof(unsigned int); if (!(index.next_ptrs = (unsigned int *) xdl_malloc(sz))) goto cleanup; memset(index.next_ptrs, 0, sz); /* lines / 4 + 1 comes from xprepare.c:xdl_prepare_ctx() */ if (xdl_cha_init(&index.rcha, sizeof(struct record), count1 / 4 + 1) < 0) goto cleanup; index.ptr_shift = line1; index.max_chain_length = 64; memset(&lcs, 0, sizeof(lcs)); if (find_lcs(&index, &lcs, line1, count1, line2, count2)) result = fall_back_to_classic_diff(&index, line1, count1, line2, count2); else { if (lcs.begin1 == 0 && lcs.begin2 == 0) { while (count1--) env->xdf1.rchg[line1++ - 1] = 1; while (count2--) env->xdf2.rchg[line2++ - 1] = 1; result = 0; } else { result = histogram_diff(xpp, env, line1, lcs.begin1 - line1, line2, lcs.begin2 - line2); if (result) goto cleanup; result = histogram_diff(xpp, env, lcs.end1 + 1, LINE_END(1) - lcs.end1, lcs.end2 + 1, LINE_END(2) - lcs.end2); if (result) goto cleanup; } } cleanup: xdl_free(index.records); xdl_free(index.line_map); xdl_free(index.next_ptrs); xdl_cha_free(&index.rcha); return result; } int xdl_do_histogram_diff(mmfile_t *file1, mmfile_t *file2, xpparam_t const *xpp, xdfenv_t *env) { if (xdl_prepare_env(file1, file2, xpp, env) < 0) return -1; return histogram_diff(xpp, env, env->xdf1.dstart + 1, env->xdf1.dend - env->xdf1.dstart + 1, env->xdf2.dstart + 1, env->xdf2.dend - env->xdf2.dstart + 1); }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/xdiff/xutils.h
/* * LibXDiff by Davide Libenzi ( File Differential Library ) * Copyright (C) 2003 Davide Libenzi * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see * <http://www.gnu.org/licenses/>. * * Davide Libenzi <[email protected]> * */ #if !defined(XUTILS_H) #define XUTILS_H long xdl_bogosqrt(long n); int xdl_emit_diffrec(char const *rec, long size, char const *pre, long psize, xdemitcb_t *ecb); int xdl_cha_init(chastore_t *cha, long isize, long icount); void xdl_cha_free(chastore_t *cha); void *xdl_cha_alloc(chastore_t *cha); long xdl_guess_lines(mmfile_t *mf, long sample); int xdl_blankline(const char *line, long size, long flags); int xdl_recmatch(const char *l1, long s1, const char *l2, long s2, long flags); unsigned long xdl_hash_record(char const **data, char const *top, long flags); unsigned int xdl_hashbits(unsigned int size); int xdl_num_out(char *out, long val); int xdl_emit_hunk_hdr(long s1, long c1, long s2, long c2, const char *func, long funclen, xdemitcb_t *ecb); int xdl_fall_back_diff(xdfenv_t *diff_env, xpparam_t const *xpp, int line1, int count1, int line2, int count2); #endif /* #if !defined(XUTILS_H) */
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/xdiff/xutils.c
/* * LibXDiff by Davide Libenzi ( File Differential Library ) * Copyright (C) 2003 Davide Libenzi * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see * <http://www.gnu.org/licenses/>. * * Davide Libenzi <[email protected]> * */ #include "xinclude.h" long xdl_bogosqrt(long n) { long i; /* * Classical integer square root approximation using shifts. */ for (i = 1; n > 0; n >>= 2) i <<= 1; return i; } int xdl_emit_diffrec(char const *rec, long size, char const *pre, long psize, xdemitcb_t *ecb) { int i = 2; mmbuffer_t mb[3]; mb[0].ptr = (char *) pre; mb[0].size = psize; mb[1].ptr = (char *) rec; mb[1].size = size; if (size > 0 && rec[size - 1] != '\n') { mb[2].ptr = (char *) "\n\\ No newline at end of file\n"; mb[2].size = strlen(mb[2].ptr); i++; } if (ecb->outf(ecb->priv, mb, i) < 0) { return -1; } return 0; } void *xdl_mmfile_first(mmfile_t *mmf, long *size) { *size = mmf->size; return mmf->ptr; } long xdl_mmfile_size(mmfile_t *mmf) { return mmf->size; } int xdl_cha_init(chastore_t *cha, long isize, long icount) { cha->head = cha->tail = NULL; cha->isize = isize; cha->nsize = icount * isize; cha->ancur = cha->sncur = NULL; cha->scurr = 0; return 0; } void xdl_cha_free(chastore_t *cha) { chanode_t *cur, *tmp; for (cur = cha->head; (tmp = cur) != NULL;) { cur = cur->next; xdl_free(tmp); } } void *xdl_cha_alloc(chastore_t *cha) { chanode_t *ancur; void *data; if (!(ancur = cha->ancur) || ancur->icurr == cha->nsize) { if (!(ancur = (chanode_t *) xdl_malloc(sizeof(chanode_t) + cha->nsize))) { return NULL; } ancur->icurr = 0; ancur->next = NULL; if (cha->tail) cha->tail->next = ancur; if (!cha->head) cha->head = ancur; cha->tail = ancur; cha->ancur = ancur; } data = (char *) ancur + sizeof(chanode_t) + ancur->icurr; ancur->icurr += cha->isize; return data; } long xdl_guess_lines(mmfile_t *mf, long sample) { long nl = 0, size, tsize = 0; char const *data, *cur, *top; if ((cur = data = xdl_mmfile_first(mf, &size)) != NULL) { for (top = data + size; nl < sample && cur < top; ) { nl++; if (!(cur = memchr(cur, '\n', top - cur))) cur = top; else cur++; } tsize += (long) (cur - data); } if (nl && tsize) nl = xdl_mmfile_size(mf) / (tsize / nl); return nl + 1; } int xdl_blankline(const char *line, long size, long flags) { long i; if (!(flags & XDF_WHITESPACE_FLAGS)) return (size <= 1); for (i = 0; i < size && XDL_ISSPACE(line[i]); i++) ; return (i == size); } /* * Have we eaten everything on the line, except for an optional * CR at the very end? */ static int ends_with_optional_cr(const char *l, long s, long i) { int complete = s && l[s-1] == '\n'; if (complete) s--; if (s == i) return 1; /* do not ignore CR at the end of an incomplete line */ if (complete && s == i + 1 && l[i] == '\r') return 1; return 0; } int xdl_recmatch(const char *l1, long s1, const char *l2, long s2, long flags) { int i1, i2; if (s1 == s2 && !memcmp(l1, l2, s1)) return 1; if (!(flags & XDF_WHITESPACE_FLAGS)) return 0; i1 = 0; i2 = 0; /* * -w matches everything that matches with -b, and -b in turn * matches everything that matches with --ignore-space-at-eol, * which in turn matches everything that matches with --ignore-cr-at-eol. * * Each flavor of ignoring needs different logic to skip whitespaces * while we have both sides to compare. */ if (flags & XDF_IGNORE_WHITESPACE) { goto skip_ws; while (i1 < s1 && i2 < s2) { if (l1[i1++] != l2[i2++]) return 0; skip_ws: while (i1 < s1 && XDL_ISSPACE(l1[i1])) i1++; while (i2 < s2 && XDL_ISSPACE(l2[i2])) i2++; } } else if (flags & XDF_IGNORE_WHITESPACE_CHANGE) { while (i1 < s1 && i2 < s2) { if (XDL_ISSPACE(l1[i1]) && XDL_ISSPACE(l2[i2])) { /* Skip matching spaces and try again */ while (i1 < s1 && XDL_ISSPACE(l1[i1])) i1++; while (i2 < s2 && XDL_ISSPACE(l2[i2])) i2++; continue; } if (l1[i1++] != l2[i2++]) return 0; } } else if (flags & XDF_IGNORE_WHITESPACE_AT_EOL) { while (i1 < s1 && i2 < s2 && l1[i1] == l2[i2]) { i1++; i2++; } } else if (flags & XDF_IGNORE_CR_AT_EOL) { /* Find the first difference and see how the line ends */ while (i1 < s1 && i2 < s2 && l1[i1] == l2[i2]) { i1++; i2++; } return (ends_with_optional_cr(l1, s1, i1) && ends_with_optional_cr(l2, s2, i2)); } /* * After running out of one side, the remaining side must have * nothing but whitespace for the lines to match. Note that * ignore-whitespace-at-eol case may break out of the loop * while there still are characters remaining on both lines. */ if (i1 < s1) { while (i1 < s1 && XDL_ISSPACE(l1[i1])) i1++; if (s1 != i1) return 0; } if (i2 < s2) { while (i2 < s2 && XDL_ISSPACE(l2[i2])) i2++; return (s2 == i2); } return 1; } static unsigned long xdl_hash_record_with_whitespace(char const **data, char const *top, long flags) { unsigned long ha = 5381; char const *ptr = *data; int cr_at_eol_only = (flags & XDF_WHITESPACE_FLAGS) == XDF_IGNORE_CR_AT_EOL; for (; ptr < top && *ptr != '\n'; ptr++) { if (cr_at_eol_only) { /* do not ignore CR at the end of an incomplete line */ if (*ptr == '\r' && (ptr + 1 < top && ptr[1] == '\n')) continue; } else if (XDL_ISSPACE(*ptr)) { const char *ptr2 = ptr; int at_eol; while (ptr + 1 < top && XDL_ISSPACE(ptr[1]) && ptr[1] != '\n') ptr++; at_eol = (top <= ptr + 1 || ptr[1] == '\n'); if (flags & XDF_IGNORE_WHITESPACE) ; /* already handled */ else if (flags & XDF_IGNORE_WHITESPACE_CHANGE && !at_eol) { ha += (ha << 5); ha ^= (unsigned long) ' '; } else if (flags & XDF_IGNORE_WHITESPACE_AT_EOL && !at_eol) { while (ptr2 != ptr + 1) { ha += (ha << 5); ha ^= (unsigned long) *ptr2; ptr2++; } } continue; } ha += (ha << 5); ha ^= (unsigned long) *ptr; } *data = ptr < top ? ptr + 1: ptr; return ha; } unsigned long xdl_hash_record(char const **data, char const *top, long flags) { unsigned long ha = 5381; char const *ptr = *data; if (flags & XDF_WHITESPACE_FLAGS) return xdl_hash_record_with_whitespace(data, top, flags); for (; ptr < top && *ptr != '\n'; ptr++) { ha += (ha << 5); ha ^= (unsigned long) *ptr; } *data = ptr < top ? ptr + 1: ptr; return ha; } unsigned int xdl_hashbits(unsigned int size) { unsigned int val = 1, bits = 0; for (; val < size && bits < CHAR_BIT * sizeof(unsigned int); val <<= 1, bits++); return bits ? bits: 1; } int xdl_num_out(char *out, long val) { char *ptr, *str = out; char buf[32]; ptr = buf + sizeof(buf) - 1; *ptr = '\0'; if (val < 0) { *--ptr = '-'; val = -val; } for (; val && ptr > buf; val /= 10) *--ptr = "0123456789"[val % 10]; if (*ptr) for (; *ptr; ptr++, str++) *str = *ptr; else *str++ = '0'; *str = '\0'; return str - out; } int xdl_emit_hunk_hdr(long s1, long c1, long s2, long c2, const char *func, long funclen, xdemitcb_t *ecb) { int nb = 0; mmbuffer_t mb; char buf[128]; memcpy(buf, "@@ -", 4); nb += 4; nb += xdl_num_out(buf + nb, c1 ? s1: s1 - 1); if (c1 != 1) { memcpy(buf + nb, ",", 1); nb += 1; nb += xdl_num_out(buf + nb, c1); } memcpy(buf + nb, " +", 2); nb += 2; nb += xdl_num_out(buf + nb, c2 ? s2: s2 - 1); if (c2 != 1) { memcpy(buf + nb, ",", 1); nb += 1; nb += xdl_num_out(buf + nb, c2); } memcpy(buf + nb, " @@", 3); nb += 3; if (func && funclen) { buf[nb++] = ' '; if (funclen > (long)(sizeof(buf) - nb - 1)) funclen = sizeof(buf) - nb - 1; memcpy(buf + nb, func, funclen); nb += funclen; } buf[nb++] = '\n'; mb.ptr = buf; mb.size = nb; if (ecb->outf(ecb->priv, &mb, 1) < 0) return -1; return 0; } int xdl_fall_back_diff(xdfenv_t *diff_env, xpparam_t const *xpp, int line1, int count1, int line2, int count2) { /* * This probably does not work outside Git, since * we have a very simple mmfile structure. * * Note: ideally, we would reuse the prepared environment, but * the libxdiff interface does not (yet) allow for diffing only * ranges of lines instead of the whole files. */ mmfile_t subfile1, subfile2; xdfenv_t env; subfile1.ptr = (char *)diff_env->xdf1.recs[line1 - 1]->ptr; subfile1.size = diff_env->xdf1.recs[line1 + count1 - 2]->ptr + diff_env->xdf1.recs[line1 + count1 - 2]->size - subfile1.ptr; subfile2.ptr = (char *)diff_env->xdf2.recs[line2 - 1]->ptr; subfile2.size = diff_env->xdf2.recs[line2 + count2 - 2]->ptr + diff_env->xdf2.recs[line2 + count2 - 2]->size - subfile2.ptr; if (xdl_do_diff(&subfile1, &subfile2, xpp, &env) < 0) return -1; memcpy(diff_env->xdf1.rchg + line1 - 1, env.xdf1.rchg, count1); memcpy(diff_env->xdf2.rchg + line2 - 1, env.xdf2.rchg, count2); xdl_free_env(&env); return 0; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/xdiff/xprepare.c
/* * LibXDiff by Davide Libenzi ( File Differential Library ) * Copyright (C) 2003 Davide Libenzi * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see * <http://www.gnu.org/licenses/>. * * Davide Libenzi <[email protected]> * */ #include "xinclude.h" #define XDL_KPDIS_RUN 4 #define XDL_MAX_EQLIMIT 1024 #define XDL_SIMSCAN_WINDOW 100 #define XDL_GUESS_NLINES1 256 #define XDL_GUESS_NLINES2 20 typedef struct s_xdlclass { struct s_xdlclass *next; unsigned long ha; char const *line; long size; long idx; long len1, len2; } xdlclass_t; typedef struct s_xdlclassifier { unsigned int hbits; long hsize; xdlclass_t **rchash; chastore_t ncha; xdlclass_t **rcrecs; long alloc; long count; long flags; } xdlclassifier_t; static int xdl_init_classifier(xdlclassifier_t *cf, long size, long flags); static void xdl_free_classifier(xdlclassifier_t *cf); static int xdl_classify_record(unsigned int pass, xdlclassifier_t *cf, xrecord_t **rhash, unsigned int hbits, xrecord_t *rec); static int xdl_prepare_ctx(unsigned int pass, mmfile_t *mf, long narec, xpparam_t const *xpp, xdlclassifier_t *cf, xdfile_t *xdf); static void xdl_free_ctx(xdfile_t *xdf); static int xdl_clean_mmatch(char const *dis, long i, long s, long e); static int xdl_cleanup_records(xdlclassifier_t *cf, xdfile_t *xdf1, xdfile_t *xdf2); static int xdl_trim_ends(xdfile_t *xdf1, xdfile_t *xdf2); static int xdl_optimize_ctxs(xdlclassifier_t *cf, xdfile_t *xdf1, xdfile_t *xdf2); static int xdl_init_classifier(xdlclassifier_t *cf, long size, long flags) { cf->flags = flags; cf->hbits = xdl_hashbits((unsigned int) size); cf->hsize = 1 << cf->hbits; if (xdl_cha_init(&cf->ncha, sizeof(xdlclass_t), size / 4 + 1) < 0) { return -1; } if (!(cf->rchash = (xdlclass_t **) xdl_malloc(cf->hsize * sizeof(xdlclass_t *)))) { xdl_cha_free(&cf->ncha); return -1; } memset(cf->rchash, 0, cf->hsize * sizeof(xdlclass_t *)); cf->alloc = size; if (!(cf->rcrecs = (xdlclass_t **) xdl_malloc(cf->alloc * sizeof(xdlclass_t *)))) { xdl_free(cf->rchash); xdl_cha_free(&cf->ncha); return -1; } cf->count = 0; return 0; } static void xdl_free_classifier(xdlclassifier_t *cf) { xdl_free(cf->rcrecs); xdl_free(cf->rchash); xdl_cha_free(&cf->ncha); } static int xdl_classify_record(unsigned int pass, xdlclassifier_t *cf, xrecord_t **rhash, unsigned int hbits, xrecord_t *rec) { long hi; char const *line; xdlclass_t *rcrec; xdlclass_t **rcrecs; line = rec->ptr; hi = (long) XDL_HASHLONG(rec->ha, cf->hbits); for (rcrec = cf->rchash[hi]; rcrec; rcrec = rcrec->next) if (rcrec->ha == rec->ha && xdl_recmatch(rcrec->line, rcrec->size, rec->ptr, rec->size, cf->flags)) break; if (!rcrec) { if (!(rcrec = xdl_cha_alloc(&cf->ncha))) { return -1; } rcrec->idx = cf->count++; if (cf->count > cf->alloc) { cf->alloc *= 2; if (!(rcrecs = (xdlclass_t **) xdl_realloc(cf->rcrecs, cf->alloc * sizeof(xdlclass_t *)))) { return -1; } cf->rcrecs = rcrecs; } cf->rcrecs[rcrec->idx] = rcrec; rcrec->line = line; rcrec->size = rec->size; rcrec->ha = rec->ha; rcrec->len1 = rcrec->len2 = 0; rcrec->next = cf->rchash[hi]; cf->rchash[hi] = rcrec; } (pass == 1) ? rcrec->len1++ : rcrec->len2++; rec->ha = (unsigned long) rcrec->idx; hi = (long) XDL_HASHLONG(rec->ha, hbits); rec->next = rhash[hi]; rhash[hi] = rec; return 0; } static int xdl_prepare_ctx(unsigned int pass, mmfile_t *mf, long narec, xpparam_t const *xpp, xdlclassifier_t *cf, xdfile_t *xdf) { unsigned int hbits; long nrec, hsize, bsize; unsigned long hav; char const *blk, *cur, *top, *prev; xrecord_t *crec; xrecord_t **recs, **rrecs; xrecord_t **rhash; unsigned long *ha; char *rchg; long *rindex; ha = NULL; rindex = NULL; rchg = NULL; rhash = NULL; recs = NULL; if (xdl_cha_init(&xdf->rcha, sizeof(xrecord_t), narec / 4 + 1) < 0) goto abort; if (!(recs = (xrecord_t **) xdl_malloc(narec * sizeof(xrecord_t *)))) goto abort; if (XDF_DIFF_ALG(xpp->flags) == XDF_HISTOGRAM_DIFF) hbits = hsize = 0; else { hbits = xdl_hashbits((unsigned int) narec); hsize = 1 << hbits; if (!(rhash = (xrecord_t **) xdl_malloc(hsize * sizeof(xrecord_t *)))) goto abort; memset(rhash, 0, hsize * sizeof(xrecord_t *)); } nrec = 0; if ((cur = blk = xdl_mmfile_first(mf, &bsize)) != NULL) { for (top = blk + bsize; cur < top; ) { prev = cur; hav = xdl_hash_record(&cur, top, xpp->flags); if (nrec >= narec) { narec *= 2; if (!(rrecs = (xrecord_t **) xdl_realloc(recs, narec * sizeof(xrecord_t *)))) goto abort; recs = rrecs; } if (!(crec = xdl_cha_alloc(&xdf->rcha))) goto abort; crec->ptr = prev; crec->size = (long) (cur - prev); crec->ha = hav; recs[nrec++] = crec; if ((XDF_DIFF_ALG(xpp->flags) != XDF_HISTOGRAM_DIFF) && xdl_classify_record(pass, cf, rhash, hbits, crec) < 0) goto abort; } } if (!(rchg = (char *) xdl_malloc((nrec + 2) * sizeof(char)))) goto abort; memset(rchg, 0, (nrec + 2) * sizeof(char)); if (!(rindex = (long *) xdl_malloc((nrec + 1) * sizeof(long)))) goto abort; if (!(ha = (unsigned long *) xdl_malloc((nrec + 1) * sizeof(unsigned long)))) goto abort; xdf->nrec = nrec; xdf->recs = recs; xdf->hbits = hbits; xdf->rhash = rhash; xdf->rchg = rchg + 1; xdf->rindex = rindex; xdf->nreff = 0; xdf->ha = ha; xdf->dstart = 0; xdf->dend = nrec - 1; return 0; abort: xdl_free(ha); xdl_free(rindex); xdl_free(rchg); xdl_free(rhash); xdl_free(recs); xdl_cha_free(&xdf->rcha); return -1; } static void xdl_free_ctx(xdfile_t *xdf) { xdl_free(xdf->rhash); xdl_free(xdf->rindex); xdl_free(xdf->rchg - 1); xdl_free(xdf->ha); xdl_free(xdf->recs); xdl_cha_free(&xdf->rcha); } int xdl_prepare_env(mmfile_t *mf1, mmfile_t *mf2, xpparam_t const *xpp, xdfenv_t *xe) { long enl1, enl2, sample; xdlclassifier_t cf; memset(&cf, 0, sizeof(cf)); /* * For histogram diff, we can afford a smaller sample size and * thus a poorer estimate of the number of lines, as the hash * table (rhash) won't be filled up/grown. The number of lines * (nrecs) will be updated correctly anyway by * xdl_prepare_ctx(). */ sample = (XDF_DIFF_ALG(xpp->flags) == XDF_HISTOGRAM_DIFF ? XDL_GUESS_NLINES2 : XDL_GUESS_NLINES1); enl1 = xdl_guess_lines(mf1, sample) + 1; enl2 = xdl_guess_lines(mf2, sample) + 1; if (XDF_DIFF_ALG(xpp->flags) != XDF_HISTOGRAM_DIFF && xdl_init_classifier(&cf, enl1 + enl2 + 1, xpp->flags) < 0) return -1; if (xdl_prepare_ctx(1, mf1, enl1, xpp, &cf, &xe->xdf1) < 0) { xdl_free_classifier(&cf); return -1; } if (xdl_prepare_ctx(2, mf2, enl2, xpp, &cf, &xe->xdf2) < 0) { xdl_free_ctx(&xe->xdf1); xdl_free_classifier(&cf); return -1; } if ((XDF_DIFF_ALG(xpp->flags) != XDF_PATIENCE_DIFF) && (XDF_DIFF_ALG(xpp->flags) != XDF_HISTOGRAM_DIFF) && xdl_optimize_ctxs(&cf, &xe->xdf1, &xe->xdf2) < 0) { xdl_free_ctx(&xe->xdf2); xdl_free_ctx(&xe->xdf1); xdl_free_classifier(&cf); return -1; } if (XDF_DIFF_ALG(xpp->flags) != XDF_HISTOGRAM_DIFF) xdl_free_classifier(&cf); return 0; } void xdl_free_env(xdfenv_t *xe) { xdl_free_ctx(&xe->xdf2); xdl_free_ctx(&xe->xdf1); } static int xdl_clean_mmatch(char const *dis, long i, long s, long e) { long r, rdis0, rpdis0, rdis1, rpdis1; /* * Limits the window the is examined during the similar-lines * scan. The loops below stops when dis[i - r] == 1 (line that * has no match), but there are corner cases where the loop * proceed all the way to the extremities by causing huge * performance penalties in case of big files. */ if (i - s > XDL_SIMSCAN_WINDOW) s = i - XDL_SIMSCAN_WINDOW; if (e - i > XDL_SIMSCAN_WINDOW) e = i + XDL_SIMSCAN_WINDOW; /* * Scans the lines before 'i' to find a run of lines that either * have no match (dis[j] == 0) or have multiple matches (dis[j] > 1). * Note that we always call this function with dis[i] > 1, so the * current line (i) is already a multimatch line. */ for (r = 1, rdis0 = 0, rpdis0 = 1; (i - r) >= s; r++) { if (!dis[i - r]) rdis0++; else if (dis[i - r] == 2) rpdis0++; else break; } /* * If the run before the line 'i' found only multimatch lines, we * return 0 and hence we don't make the current line (i) discarded. * We want to discard multimatch lines only when they appear in the * middle of runs with nomatch lines (dis[j] == 0). */ if (rdis0 == 0) return 0; for (r = 1, rdis1 = 0, rpdis1 = 1; (i + r) <= e; r++) { if (!dis[i + r]) rdis1++; else if (dis[i + r] == 2) rpdis1++; else break; } /* * If the run after the line 'i' found only multimatch lines, we * return 0 and hence we don't make the current line (i) discarded. */ if (rdis1 == 0) return 0; rdis1 += rdis0; rpdis1 += rpdis0; return rpdis1 * XDL_KPDIS_RUN < (rpdis1 + rdis1); } /* * Try to reduce the problem complexity, discard records that have no * matches on the other file. Also, lines that have multiple matches * might be potentially discarded if they happear in a run of discardable. */ static int xdl_cleanup_records(xdlclassifier_t *cf, xdfile_t *xdf1, xdfile_t *xdf2) { long i, nm, nreff, mlim; xrecord_t **recs; xdlclass_t *rcrec; char *dis, *dis1, *dis2; if (!(dis = (char *) xdl_malloc(xdf1->nrec + xdf2->nrec + 2))) { return -1; } memset(dis, 0, xdf1->nrec + xdf2->nrec + 2); dis1 = dis; dis2 = dis1 + xdf1->nrec + 1; if ((mlim = xdl_bogosqrt(xdf1->nrec)) > XDL_MAX_EQLIMIT) mlim = XDL_MAX_EQLIMIT; for (i = xdf1->dstart, recs = &xdf1->recs[xdf1->dstart]; i <= xdf1->dend; i++, recs++) { rcrec = cf->rcrecs[(*recs)->ha]; nm = rcrec ? rcrec->len2 : 0; dis1[i] = (nm == 0) ? 0: (nm >= mlim) ? 2: 1; } if ((mlim = xdl_bogosqrt(xdf2->nrec)) > XDL_MAX_EQLIMIT) mlim = XDL_MAX_EQLIMIT; for (i = xdf2->dstart, recs = &xdf2->recs[xdf2->dstart]; i <= xdf2->dend; i++, recs++) { rcrec = cf->rcrecs[(*recs)->ha]; nm = rcrec ? rcrec->len1 : 0; dis2[i] = (nm == 0) ? 0: (nm >= mlim) ? 2: 1; } for (nreff = 0, i = xdf1->dstart, recs = &xdf1->recs[xdf1->dstart]; i <= xdf1->dend; i++, recs++) { if (dis1[i] == 1 || (dis1[i] == 2 && !xdl_clean_mmatch(dis1, i, xdf1->dstart, xdf1->dend))) { xdf1->rindex[nreff] = i; xdf1->ha[nreff] = (*recs)->ha; nreff++; } else xdf1->rchg[i] = 1; } xdf1->nreff = nreff; for (nreff = 0, i = xdf2->dstart, recs = &xdf2->recs[xdf2->dstart]; i <= xdf2->dend; i++, recs++) { if (dis2[i] == 1 || (dis2[i] == 2 && !xdl_clean_mmatch(dis2, i, xdf2->dstart, xdf2->dend))) { xdf2->rindex[nreff] = i; xdf2->ha[nreff] = (*recs)->ha; nreff++; } else xdf2->rchg[i] = 1; } xdf2->nreff = nreff; xdl_free(dis); return 0; } /* * Early trim initial and terminal matching records. */ static int xdl_trim_ends(xdfile_t *xdf1, xdfile_t *xdf2) { long i, lim; xrecord_t **recs1, **recs2; recs1 = xdf1->recs; recs2 = xdf2->recs; for (i = 0, lim = XDL_MIN(xdf1->nrec, xdf2->nrec); i < lim; i++, recs1++, recs2++) if ((*recs1)->ha != (*recs2)->ha) break; xdf1->dstart = xdf2->dstart = i; recs1 = xdf1->recs + xdf1->nrec - 1; recs2 = xdf2->recs + xdf2->nrec - 1; for (lim -= i, i = 0; i < lim; i++, recs1--, recs2--) if ((*recs1)->ha != (*recs2)->ha) break; xdf1->dend = xdf1->nrec - i - 1; xdf2->dend = xdf2->nrec - i - 1; return 0; } static int xdl_optimize_ctxs(xdlclassifier_t *cf, xdfile_t *xdf1, xdfile_t *xdf2) { if (xdl_trim_ends(xdf1, xdf2) < 0 || xdl_cleanup_records(cf, xdf1, xdf2) < 0) { return -1; } return 0; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/xdiff/xemit.h
/* * LibXDiff by Davide Libenzi ( File Differential Library ) * Copyright (C) 2003 Davide Libenzi * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see * <http://www.gnu.org/licenses/>. * * Davide Libenzi <[email protected]> * */ #if !defined(XEMIT_H) #define XEMIT_H typedef int (*emit_func_t)(xdfenv_t *xe, xdchange_t *xscr, xdemitcb_t *ecb, xdemitconf_t const *xecfg); xdchange_t *xdl_get_hunk(xdchange_t **xscr, xdemitconf_t const *xecfg); int xdl_emit_diff(xdfenv_t *xe, xdchange_t *xscr, xdemitcb_t *ecb, xdemitconf_t const *xecfg); #endif /* #if !defined(XEMIT_H) */
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/xdiff/xdiff.h
/* * LibXDiff by Davide Libenzi ( File Differential Library ) * Copyright (C) 2003 Davide Libenzi * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see * <http://www.gnu.org/licenses/>. * * Davide Libenzi <[email protected]> * */ #if !defined(XDIFF_H) #define XDIFF_H #ifdef __cplusplus extern "C" { #endif /* #ifdef __cplusplus */ /* xpparm_t.flags */ #define XDF_NEED_MINIMAL (1 << 0) #define XDF_IGNORE_WHITESPACE (1 << 1) #define XDF_IGNORE_WHITESPACE_CHANGE (1 << 2) #define XDF_IGNORE_WHITESPACE_AT_EOL (1 << 3) #define XDF_IGNORE_CR_AT_EOL (1 << 4) #define XDF_WHITESPACE_FLAGS (XDF_IGNORE_WHITESPACE | \ XDF_IGNORE_WHITESPACE_CHANGE | \ XDF_IGNORE_WHITESPACE_AT_EOL | \ XDF_IGNORE_CR_AT_EOL) #define XDF_IGNORE_BLANK_LINES (1 << 7) #define XDF_PATIENCE_DIFF (1 << 14) #define XDF_HISTOGRAM_DIFF (1 << 15) #define XDF_DIFF_ALGORITHM_MASK (XDF_PATIENCE_DIFF | XDF_HISTOGRAM_DIFF) #define XDF_DIFF_ALG(x) ((x) & XDF_DIFF_ALGORITHM_MASK) #define XDF_INDENT_HEURISTIC (1 << 23) /* xdemitconf_t.flags */ #define XDL_EMIT_FUNCNAMES (1 << 0) #define XDL_EMIT_FUNCCONTEXT (1 << 2) #define XDL_MMB_READONLY (1 << 0) #define XDL_MMF_ATOMIC (1 << 0) #define XDL_BDOP_INS 1 #define XDL_BDOP_CPY 2 #define XDL_BDOP_INSB 3 /* merge simplification levels */ #define XDL_MERGE_MINIMAL 0 #define XDL_MERGE_EAGER 1 #define XDL_MERGE_ZEALOUS 2 #define XDL_MERGE_ZEALOUS_ALNUM 3 /* merge favor modes */ #define XDL_MERGE_FAVOR_OURS 1 #define XDL_MERGE_FAVOR_THEIRS 2 #define XDL_MERGE_FAVOR_UNION 3 /* merge output styles */ #define XDL_MERGE_DIFF3 1 typedef struct s_mmfile { char *ptr; size_t size; } mmfile_t; typedef struct s_mmbuffer { char *ptr; size_t size; } mmbuffer_t; typedef struct s_xpparam { unsigned long flags; /* See Documentation/diff-options.txt. */ char **anchors; size_t anchors_nr; } xpparam_t; typedef struct s_xdemitcb { void *priv; int (*outf)(void *, mmbuffer_t *, int); } xdemitcb_t; typedef long (*find_func_t)(const char *line, long line_len, char *buffer, long buffer_size, void *priv); typedef int (*xdl_emit_hunk_consume_func_t)(long start_a, long count_a, long start_b, long count_b, void *cb_data); typedef struct s_xdemitconf { long ctxlen; long interhunkctxlen; unsigned long flags; find_func_t find_func; void *find_func_priv; xdl_emit_hunk_consume_func_t hunk_func; } xdemitconf_t; typedef struct s_bdiffparam { long bsize; } bdiffparam_t; #define xdl_malloc(x) git__malloc(x) #define xdl_free(ptr) git__free(ptr) #define xdl_realloc(ptr,x) git__realloc(ptr,x) void *xdl_mmfile_first(mmfile_t *mmf, long *size); long xdl_mmfile_size(mmfile_t *mmf); int xdl_diff(mmfile_t *mf1, mmfile_t *mf2, xpparam_t const *xpp, xdemitconf_t const *xecfg, xdemitcb_t *ecb); typedef struct s_xmparam { xpparam_t xpp; int marker_size; int level; int favor; int style; const char *ancestor; /* label for orig */ const char *file1; /* label for mf1 */ const char *file2; /* label for mf2 */ } xmparam_t; #define DEFAULT_CONFLICT_MARKER_SIZE 7 int xdl_merge(mmfile_t *orig, mmfile_t *mf1, mmfile_t *mf2, xmparam_t const *xmp, mmbuffer_t *result); #ifdef __cplusplus } #endif /* #ifdef __cplusplus */ #endif /* #if !defined(XDIFF_H) */
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/xdiff/xinclude.h
/* * LibXDiff by Davide Libenzi ( File Differential Library ) * Copyright (C) 2003 Davide Libenzi * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see * <http://www.gnu.org/licenses/>. * * Davide Libenzi <[email protected]> * */ #if !defined(XINCLUDE_H) #define XINCLUDE_H #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #ifdef _WIN32 #else #include <unistd.h> #endif #include "xmacros.h" #include "xdiff.h" #include "xtypes.h" #include "xutils.h" #include "xprepare.h" #include "xdiffi.h" #include "xemit.h" #include "common.h" #endif /* #if !defined(XINCLUDE_H) */
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/xdiff/xdiffi.h
/* * LibXDiff by Davide Libenzi ( File Differential Library ) * Copyright (C) 2003 Davide Libenzi * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see * <http://www.gnu.org/licenses/>. * * Davide Libenzi <[email protected]> * */ #if !defined(XDIFFI_H) #define XDIFFI_H typedef struct s_diffdata { long nrec; unsigned long const *ha; long *rindex; char *rchg; } diffdata_t; typedef struct s_xdalgoenv { long mxcost; long snake_cnt; long heur_min; } xdalgoenv_t; typedef struct s_xdchange { struct s_xdchange *next; long i1, i2; long chg1, chg2; int ignore; } xdchange_t; int xdl_recs_cmp(diffdata_t *dd1, long off1, long lim1, diffdata_t *dd2, long off2, long lim2, long *kvdf, long *kvdb, int need_min, xdalgoenv_t *xenv); int xdl_do_diff(mmfile_t *mf1, mmfile_t *mf2, xpparam_t const *xpp, xdfenv_t *xe); int xdl_change_compact(xdfile_t *xdf, xdfile_t *xdfo, long flags); int xdl_build_script(xdfenv_t *xe, xdchange_t **xscr); void xdl_free_script(xdchange_t *xscr); int xdl_emit_diff(xdfenv_t *xe, xdchange_t *xscr, xdemitcb_t *ecb, xdemitconf_t const *xecfg); int xdl_do_patience_diff(mmfile_t *mf1, mmfile_t *mf2, xpparam_t const *xpp, xdfenv_t *env); int xdl_do_histogram_diff(mmfile_t *mf1, mmfile_t *mf2, xpparam_t const *xpp, xdfenv_t *env); #endif /* #if !defined(XDIFFI_H) */
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/xdiff/xpatience.c
/* * LibXDiff by Davide Libenzi ( File Differential Library ) * Copyright (C) 2003-2016 Davide Libenzi, Johannes E. Schindelin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see * <http://www.gnu.org/licenses/>. * * Davide Libenzi <[email protected]> * */ #include "xinclude.h" #include "xtypes.h" #include "xdiff.h" /* * The basic idea of patience diff is to find lines that are unique in * both files. These are intuitively the ones that we want to see as * common lines. * * The maximal ordered sequence of such line pairs (where ordered means * that the order in the sequence agrees with the order of the lines in * both files) naturally defines an initial set of common lines. * * Now, the algorithm tries to extend the set of common lines by growing * the line ranges where the files have identical lines. * * Between those common lines, the patience diff algorithm is applied * recursively, until no unique line pairs can be found; these line ranges * are handled by the well-known Myers algorithm. */ #define NON_UNIQUE ULONG_MAX /* * This is a hash mapping from line hash to line numbers in the first and * second file. */ struct hashmap { int nr, alloc; struct entry { unsigned long hash; /* * 0 = unused entry, 1 = first line, 2 = second, etc. * line2 is NON_UNIQUE if the line is not unique * in either the first or the second file. */ unsigned long line1, line2; /* * "next" & "previous" are used for the longest common * sequence; * initially, "next" reflects only the order in file1. */ struct entry *next, *previous; /* * If 1, this entry can serve as an anchor. See * Documentation/diff-options.txt for more information. */ unsigned anchor : 1; } *entries, *first, *last; /* were common records found? */ unsigned long has_matches; mmfile_t *file1, *file2; xdfenv_t *env; xpparam_t const *xpp; }; static int is_anchor(xpparam_t const *xpp, const char *line) { unsigned long i; for (i = 0; i < xpp->anchors_nr; i++) { if (!strncmp(line, xpp->anchors[i], strlen(xpp->anchors[i]))) return 1; } return 0; } /* The argument "pass" is 1 for the first file, 2 for the second. */ static void insert_record(xpparam_t const *xpp, int line, struct hashmap *map, int pass) { xrecord_t **records = pass == 1 ? map->env->xdf1.recs : map->env->xdf2.recs; xrecord_t *record = records[line - 1], *other; /* * After xdl_prepare_env() (or more precisely, due to * xdl_classify_record()), the "ha" member of the records (AKA lines) * is _not_ the hash anymore, but a linearized version of it. In * other words, the "ha" member is guaranteed to start with 0 and * the second record's ha can only be 0 or 1, etc. * * So we multiply ha by 2 in the hope that the hashing was * "unique enough". */ int index = (int)((record->ha << 1) % map->alloc); while (map->entries[index].line1) { other = map->env->xdf1.recs[map->entries[index].line1 - 1]; if (map->entries[index].hash != record->ha || !xdl_recmatch(record->ptr, record->size, other->ptr, other->size, map->xpp->flags)) { if (++index >= map->alloc) index = 0; continue; } if (pass == 2) map->has_matches = 1; if (pass == 1 || map->entries[index].line2) map->entries[index].line2 = NON_UNIQUE; else map->entries[index].line2 = line; return; } if (pass == 2) return; map->entries[index].line1 = line; map->entries[index].hash = record->ha; map->entries[index].anchor = is_anchor(xpp, map->env->xdf1.recs[line - 1]->ptr); if (!map->first) map->first = map->entries + index; if (map->last) { map->last->next = map->entries + index; map->entries[index].previous = map->last; } map->last = map->entries + index; map->nr++; } /* * This function has to be called for each recursion into the inter-hunk * parts, as previously non-unique lines can become unique when being * restricted to a smaller part of the files. * * It is assumed that env has been prepared using xdl_prepare(). */ static int fill_hashmap(mmfile_t *file1, mmfile_t *file2, xpparam_t const *xpp, xdfenv_t *env, struct hashmap *result, int line1, int count1, int line2, int count2) { result->file1 = file1; result->file2 = file2; result->xpp = xpp; result->env = env; /* We know exactly how large we want the hash map */ result->alloc = count1 * 2; result->entries = (struct entry *) xdl_malloc(result->alloc * sizeof(struct entry)); if (!result->entries) return -1; memset(result->entries, 0, result->alloc * sizeof(struct entry)); /* First, fill with entries from the first file */ while (count1--) insert_record(xpp, line1++, result, 1); /* Then search for matches in the second file */ while (count2--) insert_record(xpp, line2++, result, 2); return 0; } /* * Find the longest sequence with a smaller last element (meaning a smaller * line2, as we construct the sequence with entries ordered by line1). */ static int binary_search(struct entry **sequence, int longest, struct entry *entry) { int left = -1, right = longest; while (left + 1 < right) { int middle = left + (right - left) / 2; /* by construction, no two entries can be equal */ if (sequence[middle]->line2 > entry->line2) right = middle; else left = middle; } /* return the index in "sequence", _not_ the sequence length */ return left; } /* * The idea is to start with the list of common unique lines sorted by * the order in file1. For each of these pairs, the longest (partial) * sequence whose last element's line2 is smaller is determined. * * For efficiency, the sequences are kept in a list containing exactly one * item per sequence length: the sequence with the smallest last * element (in terms of line2). */ static struct entry *find_longest_common_sequence(struct hashmap *map) { struct entry **sequence = xdl_malloc(map->nr * sizeof(struct entry *)); int longest = 0, i; struct entry *entry; /* * If not -1, this entry in sequence must never be overridden. * Therefore, overriding entries before this has no effect, so * do not do that either. */ int anchor_i = -1; if (!sequence) return NULL; for (entry = map->first; entry; entry = entry->next) { if (!entry->line2 || entry->line2 == NON_UNIQUE) continue; i = binary_search(sequence, longest, entry); entry->previous = i < 0 ? NULL : sequence[i]; ++i; if (i <= anchor_i) continue; sequence[i] = entry; if (entry->anchor) { anchor_i = i; longest = anchor_i + 1; } else if (i == longest) { longest++; } } /* No common unique lines were found */ if (!longest) { xdl_free(sequence); return NULL; } /* Iterate starting at the last element, adjusting the "next" members */ entry = sequence[longest - 1]; entry->next = NULL; while (entry->previous) { entry->previous->next = entry; entry = entry->previous; } xdl_free(sequence); return entry; } static int match(struct hashmap *map, int line1, int line2) { xrecord_t *record1 = map->env->xdf1.recs[line1 - 1]; xrecord_t *record2 = map->env->xdf2.recs[line2 - 1]; return xdl_recmatch(record1->ptr, record1->size, record2->ptr, record2->size, map->xpp->flags); } static int patience_diff(mmfile_t *file1, mmfile_t *file2, xpparam_t const *xpp, xdfenv_t *env, int line1, int count1, int line2, int count2); static int walk_common_sequence(struct hashmap *map, struct entry *first, int line1, int count1, int line2, int count2) { int end1 = line1 + count1, end2 = line2 + count2; int next1, next2; for (;;) { /* Try to grow the line ranges of common lines */ if (first) { next1 = first->line1; next2 = first->line2; while (next1 > line1 && next2 > line2 && match(map, next1 - 1, next2 - 1)) { next1--; next2--; } } else { next1 = end1; next2 = end2; } while (line1 < next1 && line2 < next2 && match(map, line1, line2)) { line1++; line2++; } /* Recurse */ if (next1 > line1 || next2 > line2) { struct hashmap submap; memset(&submap, 0, sizeof(submap)); if (patience_diff(map->file1, map->file2, map->xpp, map->env, line1, next1 - line1, line2, next2 - line2)) return -1; } if (!first) return 0; while (first->next && first->next->line1 == first->line1 + 1 && first->next->line2 == first->line2 + 1) first = first->next; line1 = first->line1 + 1; line2 = first->line2 + 1; first = first->next; } } static int fall_back_to_classic_diff(struct hashmap *map, int line1, int count1, int line2, int count2) { xpparam_t xpp; xpp.flags = map->xpp->flags & ~XDF_DIFF_ALGORITHM_MASK; return xdl_fall_back_diff(map->env, &xpp, line1, count1, line2, count2); } /* * Recursively find the longest common sequence of unique lines, * and if none was found, ask xdl_do_diff() to do the job. * * This function assumes that env was prepared with xdl_prepare_env(). */ static int patience_diff(mmfile_t *file1, mmfile_t *file2, xpparam_t const *xpp, xdfenv_t *env, int line1, int count1, int line2, int count2) { struct hashmap map; struct entry *first; int result = 0; /* trivial case: one side is empty */ if (!count1) { while(count2--) env->xdf2.rchg[line2++ - 1] = 1; return 0; } else if (!count2) { while(count1--) env->xdf1.rchg[line1++ - 1] = 1; return 0; } memset(&map, 0, sizeof(map)); if (fill_hashmap(file1, file2, xpp, env, &map, line1, count1, line2, count2)) return -1; /* are there any matching lines at all? */ if (!map.has_matches) { while(count1--) env->xdf1.rchg[line1++ - 1] = 1; while(count2--) env->xdf2.rchg[line2++ - 1] = 1; xdl_free(map.entries); return 0; } first = find_longest_common_sequence(&map); if (first) result = walk_common_sequence(&map, first, line1, count1, line2, count2); else result = fall_back_to_classic_diff(&map, line1, count1, line2, count2); xdl_free(map.entries); return result; } int xdl_do_patience_diff(mmfile_t *file1, mmfile_t *file2, xpparam_t const *xpp, xdfenv_t *env) { if (xdl_prepare_env(file1, file2, xpp, env) < 0) return -1; /* environment is cleaned up in xdl_diff() */ return patience_diff(file1, file2, xpp, env, 1, env->xdf1.nrec, 1, env->xdf2.nrec); }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/xdiff/xdiffi.c
/* * LibXDiff by Davide Libenzi ( File Differential Library ) * Copyright (C) 2003 Davide Libenzi * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see * <http://www.gnu.org/licenses/>. * * Davide Libenzi <[email protected]> * */ #include "xinclude.h" #include "integer.h" #define XDL_MAX_COST_MIN 256 #define XDL_HEUR_MIN_COST 256 #define XDL_LINE_MAX (long)((1UL << (CHAR_BIT * sizeof(long) - 1)) - 1) #define XDL_SNAKE_CNT 20 #define XDL_K_HEUR 4 /** Declare a function as always inlined. */ #if defined(_MSC_VER) # define XDL_INLINE(type) static __inline type #elif defined(__GNUC__) # define XDL_INLINE(type) static __inline__ type #else # define XDL_INLINE(type) static type #endif typedef struct s_xdpsplit { long i1, i2; int min_lo, min_hi; } xdpsplit_t; static long xdl_split(unsigned long const *ha1, long off1, long lim1, unsigned long const *ha2, long off2, long lim2, long *kvdf, long *kvdb, int need_min, xdpsplit_t *spl, xdalgoenv_t *xenv); static xdchange_t *xdl_add_change(xdchange_t *xscr, long i1, long i2, long chg1, long chg2); /* * See "An O(ND) Difference Algorithm and its Variations", by Eugene Myers. * Basically considers a "box" (off1, off2, lim1, lim2) and scan from both * the forward diagonal starting from (off1, off2) and the backward diagonal * starting from (lim1, lim2). If the K values on the same diagonal crosses * returns the furthest point of reach. We might end up having to expensive * cases using this algorithm is full, so a little bit of heuristic is needed * to cut the search and to return a suboptimal point. */ static long xdl_split(unsigned long const *ha1, long off1, long lim1, unsigned long const *ha2, long off2, long lim2, long *kvdf, long *kvdb, int need_min, xdpsplit_t *spl, xdalgoenv_t *xenv) { long dmin = off1 - lim2, dmax = lim1 - off2; long fmid = off1 - off2, bmid = lim1 - lim2; long odd = (fmid - bmid) & 1; long fmin = fmid, fmax = fmid; long bmin = bmid, bmax = bmid; long ec, d, i1, i2, prev1, best, dd, v, k; /* * Set initial diagonal values for both forward and backward path. */ kvdf[fmid] = off1; kvdb[bmid] = lim1; for (ec = 1;; ec++) { int got_snake = 0; /* * We need to extent the diagonal "domain" by one. If the next * values exits the box boundaries we need to change it in the * opposite direction because (max - min) must be a power of two. * Also we initialize the external K value to -1 so that we can * avoid extra conditions check inside the core loop. */ if (fmin > dmin) kvdf[--fmin - 1] = -1; else ++fmin; if (fmax < dmax) kvdf[++fmax + 1] = -1; else --fmax; for (d = fmax; d >= fmin; d -= 2) { if (kvdf[d - 1] >= kvdf[d + 1]) i1 = kvdf[d - 1] + 1; else i1 = kvdf[d + 1]; prev1 = i1; i2 = i1 - d; for (; i1 < lim1 && i2 < lim2 && ha1[i1] == ha2[i2]; i1++, i2++); if (i1 - prev1 > xenv->snake_cnt) got_snake = 1; kvdf[d] = i1; if (odd && bmin <= d && d <= bmax && kvdb[d] <= i1) { spl->i1 = i1; spl->i2 = i2; spl->min_lo = spl->min_hi = 1; return ec; } } /* * We need to extent the diagonal "domain" by one. If the next * values exits the box boundaries we need to change it in the * opposite direction because (max - min) must be a power of two. * Also we initialize the external K value to -1 so that we can * avoid extra conditions check inside the core loop. */ if (bmin > dmin) kvdb[--bmin - 1] = XDL_LINE_MAX; else ++bmin; if (bmax < dmax) kvdb[++bmax + 1] = XDL_LINE_MAX; else --bmax; for (d = bmax; d >= bmin; d -= 2) { if (kvdb[d - 1] < kvdb[d + 1]) i1 = kvdb[d - 1]; else i1 = kvdb[d + 1] - 1; prev1 = i1; i2 = i1 - d; for (; i1 > off1 && i2 > off2 && ha1[i1 - 1] == ha2[i2 - 1]; i1--, i2--); if (prev1 - i1 > xenv->snake_cnt) got_snake = 1; kvdb[d] = i1; if (!odd && fmin <= d && d <= fmax && i1 <= kvdf[d]) { spl->i1 = i1; spl->i2 = i2; spl->min_lo = spl->min_hi = 1; return ec; } } if (need_min) continue; /* * If the edit cost is above the heuristic trigger and if * we got a good snake, we sample current diagonals to see * if some of the, have reached an "interesting" path. Our * measure is a function of the distance from the diagonal * corner (i1 + i2) penalized with the distance from the * mid diagonal itself. If this value is above the current * edit cost times a magic factor (XDL_K_HEUR) we consider * it interesting. */ if (got_snake && ec > xenv->heur_min) { for (best = 0, d = fmax; d >= fmin; d -= 2) { dd = d > fmid ? d - fmid: fmid - d; i1 = kvdf[d]; i2 = i1 - d; v = (i1 - off1) + (i2 - off2) - dd; if (v > XDL_K_HEUR * ec && v > best && off1 + xenv->snake_cnt <= i1 && i1 < lim1 && off2 + xenv->snake_cnt <= i2 && i2 < lim2) { for (k = 1; ha1[i1 - k] == ha2[i2 - k]; k++) if (k == xenv->snake_cnt) { best = v; spl->i1 = i1; spl->i2 = i2; break; } } } if (best > 0) { spl->min_lo = 1; spl->min_hi = 0; return ec; } for (best = 0, d = bmax; d >= bmin; d -= 2) { dd = d > bmid ? d - bmid: bmid - d; i1 = kvdb[d]; i2 = i1 - d; v = (lim1 - i1) + (lim2 - i2) - dd; if (v > XDL_K_HEUR * ec && v > best && off1 < i1 && i1 <= lim1 - xenv->snake_cnt && off2 < i2 && i2 <= lim2 - xenv->snake_cnt) { for (k = 0; ha1[i1 + k] == ha2[i2 + k]; k++) if (k == xenv->snake_cnt - 1) { best = v; spl->i1 = i1; spl->i2 = i2; break; } } } if (best > 0) { spl->min_lo = 0; spl->min_hi = 1; return ec; } } /* * Enough is enough. We spent too much time here and now we collect * the furthest reaching path using the (i1 + i2) measure. */ if (ec >= xenv->mxcost) { long fbest, fbest1, bbest, bbest1; fbest = fbest1 = -1; for (d = fmax; d >= fmin; d -= 2) { i1 = XDL_MIN(kvdf[d], lim1); i2 = i1 - d; if (lim2 < i2) i1 = lim2 + d, i2 = lim2; if (fbest < i1 + i2) { fbest = i1 + i2; fbest1 = i1; } } bbest = bbest1 = XDL_LINE_MAX; for (d = bmax; d >= bmin; d -= 2) { i1 = XDL_MAX(off1, kvdb[d]); i2 = i1 - d; if (i2 < off2) i1 = off2 + d, i2 = off2; if (i1 + i2 < bbest) { bbest = i1 + i2; bbest1 = i1; } } if ((lim1 + lim2) - bbest < fbest - (off1 + off2)) { spl->i1 = fbest1; spl->i2 = fbest - fbest1; spl->min_lo = 1; spl->min_hi = 0; } else { spl->i1 = bbest1; spl->i2 = bbest - bbest1; spl->min_lo = 0; spl->min_hi = 1; } return ec; } } } /* * Rule: "Divide et Impera". Recursively split the box in sub-boxes by calling * the box splitting function. Note that the real job (marking changed lines) * is done in the two boundary reaching checks. */ int xdl_recs_cmp(diffdata_t *dd1, long off1, long lim1, diffdata_t *dd2, long off2, long lim2, long *kvdf, long *kvdb, int need_min, xdalgoenv_t *xenv) { unsigned long const *ha1 = dd1->ha, *ha2 = dd2->ha; /* * Shrink the box by walking through each diagonal snake (SW and NE). */ for (; off1 < lim1 && off2 < lim2 && ha1[off1] == ha2[off2]; off1++, off2++); for (; off1 < lim1 && off2 < lim2 && ha1[lim1 - 1] == ha2[lim2 - 1]; lim1--, lim2--); /* * If one dimension is empty, then all records on the other one must * be obviously changed. */ if (off1 == lim1) { char *rchg2 = dd2->rchg; long *rindex2 = dd2->rindex; for (; off2 < lim2; off2++) rchg2[rindex2[off2]] = 1; } else if (off2 == lim2) { char *rchg1 = dd1->rchg; long *rindex1 = dd1->rindex; for (; off1 < lim1; off1++) rchg1[rindex1[off1]] = 1; } else { xdpsplit_t spl; spl.i1 = spl.i2 = 0; /* * Divide ... */ if (xdl_split(ha1, off1, lim1, ha2, off2, lim2, kvdf, kvdb, need_min, &spl, xenv) < 0) { return -1; } /* * ... et Impera. */ if (xdl_recs_cmp(dd1, off1, spl.i1, dd2, off2, spl.i2, kvdf, kvdb, spl.min_lo, xenv) < 0 || xdl_recs_cmp(dd1, spl.i1, lim1, dd2, spl.i2, lim2, kvdf, kvdb, spl.min_hi, xenv) < 0) { return -1; } } return 0; } int xdl_do_diff(mmfile_t *mf1, mmfile_t *mf2, xpparam_t const *xpp, xdfenv_t *xe) { size_t ndiags, allocsize; long *kvd, *kvdf, *kvdb; xdalgoenv_t xenv; diffdata_t dd1, dd2; if (XDF_DIFF_ALG(xpp->flags) == XDF_PATIENCE_DIFF) return xdl_do_patience_diff(mf1, mf2, xpp, xe); if (XDF_DIFF_ALG(xpp->flags) == XDF_HISTOGRAM_DIFF) return xdl_do_histogram_diff(mf1, mf2, xpp, xe); if (xdl_prepare_env(mf1, mf2, xpp, xe) < 0) { return -1; } /* * Allocate and setup K vectors to be used by the differential algorithm. * One is to store the forward path and one to store the backward path. */ GIT_ERROR_CHECK_ALLOC_ADD3(&ndiags, xe->xdf1.nreff, xe->xdf2.nreff, 3); GIT_ERROR_CHECK_ALLOC_MULTIPLY(&allocsize, ndiags, 2); GIT_ERROR_CHECK_ALLOC_ADD(&allocsize, allocsize, 2); GIT_ERROR_CHECK_ALLOC_MULTIPLY(&allocsize, allocsize, sizeof(long)); if (!(kvd = (long *) xdl_malloc(allocsize))) { xdl_free_env(xe); return -1; } kvdf = kvd; kvdb = kvdf + ndiags; kvdf += xe->xdf2.nreff + 1; kvdb += xe->xdf2.nreff + 1; xenv.mxcost = xdl_bogosqrt(ndiags); if (xenv.mxcost < XDL_MAX_COST_MIN) xenv.mxcost = XDL_MAX_COST_MIN; xenv.snake_cnt = XDL_SNAKE_CNT; xenv.heur_min = XDL_HEUR_MIN_COST; dd1.nrec = xe->xdf1.nreff; dd1.ha = xe->xdf1.ha; dd1.rchg = xe->xdf1.rchg; dd1.rindex = xe->xdf1.rindex; dd2.nrec = xe->xdf2.nreff; dd2.ha = xe->xdf2.ha; dd2.rchg = xe->xdf2.rchg; dd2.rindex = xe->xdf2.rindex; if (xdl_recs_cmp(&dd1, 0, dd1.nrec, &dd2, 0, dd2.nrec, kvdf, kvdb, (xpp->flags & XDF_NEED_MINIMAL) != 0, &xenv) < 0) { xdl_free(kvd); xdl_free_env(xe); return -1; } xdl_free(kvd); return 0; } static xdchange_t *xdl_add_change(xdchange_t *xscr, long i1, long i2, long chg1, long chg2) { xdchange_t *xch; if (!(xch = (xdchange_t *) xdl_malloc(sizeof(xdchange_t)))) return NULL; xch->next = xscr; xch->i1 = i1; xch->i2 = i2; xch->chg1 = chg1; xch->chg2 = chg2; xch->ignore = 0; return xch; } static int recs_match(xrecord_t *rec1, xrecord_t *rec2, long flags) { return (rec1->ha == rec2->ha && xdl_recmatch(rec1->ptr, rec1->size, rec2->ptr, rec2->size, flags)); } /* * If a line is indented more than this, get_indent() just returns this value. * This avoids having to do absurd amounts of work for data that are not * human-readable text, and also ensures that the output of get_indent fits within * an int. */ #define MAX_INDENT 200 /* * Return the amount of indentation of the specified line, treating TAB as 8 * columns. Return -1 if line is empty or contains only whitespace. Clamp the * output value at MAX_INDENT. */ static int get_indent(xrecord_t *rec) { long i; int ret = 0; for (i = 0; i < rec->size; i++) { char c = rec->ptr[i]; if (!XDL_ISSPACE(c)) return ret; else if (c == ' ') ret += 1; else if (c == '\t') ret += 8 - ret % 8; /* ignore other whitespace characters */ if (ret >= MAX_INDENT) return MAX_INDENT; } /* The line contains only whitespace. */ return -1; } /* * If more than this number of consecutive blank rows are found, just return this * value. This avoids requiring O(N^2) work for pathological cases, and also * ensures that the output of score_split fits in an int. */ #define MAX_BLANKS 20 /* Characteristics measured about a hypothetical split position. */ struct split_measurement { /* * Is the split at the end of the file (aside from any blank lines)? */ int end_of_file; /* * How much is the line immediately following the split indented (or -1 if * the line is blank): */ int indent; /* * How many consecutive lines above the split are blank? */ int pre_blank; /* * How much is the nearest non-blank line above the split indented (or -1 * if there is no such line)? */ int pre_indent; /* * How many lines after the line following the split are blank? */ int post_blank; /* * How much is the nearest non-blank line after the line following the * split indented (or -1 if there is no such line)? */ int post_indent; }; struct split_score { /* The effective indent of this split (smaller is preferred). */ int effective_indent; /* Penalty for this split (smaller is preferred). */ int penalty; }; /* * Fill m with information about a hypothetical split of xdf above line split. */ static void measure_split(const xdfile_t *xdf, long split, struct split_measurement *m) { long i; if (split >= xdf->nrec) { m->end_of_file = 1; m->indent = -1; } else { m->end_of_file = 0; m->indent = get_indent(xdf->recs[split]); } m->pre_blank = 0; m->pre_indent = -1; for (i = split - 1; i >= 0; i--) { m->pre_indent = get_indent(xdf->recs[i]); if (m->pre_indent != -1) break; m->pre_blank += 1; if (m->pre_blank == MAX_BLANKS) { m->pre_indent = 0; break; } } m->post_blank = 0; m->post_indent = -1; for (i = split + 1; i < xdf->nrec; i++) { m->post_indent = get_indent(xdf->recs[i]); if (m->post_indent != -1) break; m->post_blank += 1; if (m->post_blank == MAX_BLANKS) { m->post_indent = 0; break; } } } /* * The empirically-determined weight factors used by score_split() below. * Larger values means that the position is a less favorable place to split. * * Note that scores are only ever compared against each other, so multiplying * all of these weight/penalty values by the same factor wouldn't change the * heuristic's behavior. Still, we need to set that arbitrary scale *somehow*. * In practice, these numbers are chosen to be large enough that they can be * adjusted relative to each other with sufficient precision despite using * integer math. */ /* Penalty if there are no non-blank lines before the split */ #define START_OF_FILE_PENALTY 1 /* Penalty if there are no non-blank lines after the split */ #define END_OF_FILE_PENALTY 21 /* Multiplier for the number of blank lines around the split */ #define TOTAL_BLANK_WEIGHT (-30) /* Multiplier for the number of blank lines after the split */ #define POST_BLANK_WEIGHT 6 /* * Penalties applied if the line is indented more than its predecessor */ #define RELATIVE_INDENT_PENALTY (-4) #define RELATIVE_INDENT_WITH_BLANK_PENALTY 10 /* * Penalties applied if the line is indented less than both its predecessor and * its successor */ #define RELATIVE_OUTDENT_PENALTY 24 #define RELATIVE_OUTDENT_WITH_BLANK_PENALTY 17 /* * Penalties applied if the line is indented less than its predecessor but not * less than its successor */ #define RELATIVE_DEDENT_PENALTY 23 #define RELATIVE_DEDENT_WITH_BLANK_PENALTY 17 /* * We only consider whether the sum of the effective indents for splits are * less than (-1), equal to (0), or greater than (+1) each other. The resulting * value is multiplied by the following weight and combined with the penalty to * determine the better of two scores. */ #define INDENT_WEIGHT 60 /* * Compute a badness score for the hypothetical split whose measurements are * stored in m. The weight factors were determined empirically using the tools and * corpus described in * * https://github.com/mhagger/diff-slider-tools * * Also see that project if you want to improve the weights based on, for example, * a larger or more diverse corpus. */ static void score_add_split(const struct split_measurement *m, struct split_score *s) { /* * A place to accumulate penalty factors (positive makes this index more * favored): */ int post_blank, total_blank, indent, any_blanks; if (m->pre_indent == -1 && m->pre_blank == 0) s->penalty += START_OF_FILE_PENALTY; if (m->end_of_file) s->penalty += END_OF_FILE_PENALTY; /* * Set post_blank to the number of blank lines following the split, * including the line immediately after the split: */ post_blank = (m->indent == -1) ? 1 + m->post_blank : 0; total_blank = m->pre_blank + post_blank; /* Penalties based on nearby blank lines: */ s->penalty += TOTAL_BLANK_WEIGHT * total_blank; s->penalty += POST_BLANK_WEIGHT * post_blank; if (m->indent != -1) indent = m->indent; else indent = m->post_indent; any_blanks = (total_blank != 0); /* Note that the effective indent is -1 at the end of the file: */ s->effective_indent += indent; if (indent == -1) { /* No additional adjustments needed. */ } else if (m->pre_indent == -1) { /* No additional adjustments needed. */ } else if (indent > m->pre_indent) { /* * The line is indented more than its predecessor. */ s->penalty += any_blanks ? RELATIVE_INDENT_WITH_BLANK_PENALTY : RELATIVE_INDENT_PENALTY; } else if (indent == m->pre_indent) { /* * The line has the same indentation level as its predecessor. * No additional adjustments needed. */ } else { /* * The line is indented less than its predecessor. It could be * the block terminator of the previous block, but it could * also be the start of a new block (e.g., an "else" block, or * maybe the previous block didn't have a block terminator). * Try to distinguish those cases based on what comes next: */ if (m->post_indent != -1 && m->post_indent > indent) { /* * The following line is indented more. So it is likely * that this line is the start of a block. */ s->penalty += any_blanks ? RELATIVE_OUTDENT_WITH_BLANK_PENALTY : RELATIVE_OUTDENT_PENALTY; } else { /* * That was probably the end of a block. */ s->penalty += any_blanks ? RELATIVE_DEDENT_WITH_BLANK_PENALTY : RELATIVE_DEDENT_PENALTY; } } } static int score_cmp(struct split_score *s1, struct split_score *s2) { /* -1 if s1.effective_indent < s2->effective_indent, etc. */ int cmp_indents = ((s1->effective_indent > s2->effective_indent) - (s1->effective_indent < s2->effective_indent)); return INDENT_WEIGHT * cmp_indents + (s1->penalty - s2->penalty); } /* * Represent a group of changed lines in an xdfile_t (i.e., a contiguous group * of lines that was inserted or deleted from the corresponding version of the * file). We consider there to be such a group at the beginning of the file, at * the end of the file, and between any two unchanged lines, though most such * groups will usually be empty. * * If the first line in a group is equal to the line following the group, then * the group can be slid down. Similarly, if the last line in a group is equal * to the line preceding the group, then the group can be slid up. See * group_slide_down() and group_slide_up(). * * Note that loops that are testing for changed lines in xdf->rchg do not need * index bounding since the array is prepared with a zero at position -1 and N. */ struct xdlgroup { /* * The index of the first changed line in the group, or the index of * the unchanged line above which the (empty) group is located. */ long start; /* * The index of the first unchanged line after the group. For an empty * group, end is equal to start. */ long end; }; /* * Initialize g to point at the first group in xdf. */ static void group_init(xdfile_t *xdf, struct xdlgroup *g) { g->start = g->end = 0; while (xdf->rchg[g->end]) g->end++; } /* * Move g to describe the next (possibly empty) group in xdf and return 0. If g * is already at the end of the file, do nothing and return -1. */ XDL_INLINE(int) group_next(xdfile_t *xdf, struct xdlgroup *g) { if (g->end == xdf->nrec) return -1; g->start = g->end + 1; for (g->end = g->start; xdf->rchg[g->end]; g->end++) ; return 0; } /* * Move g to describe the previous (possibly empty) group in xdf and return 0. * If g is already at the beginning of the file, do nothing and return -1. */ XDL_INLINE(int) group_previous(xdfile_t *xdf, struct xdlgroup *g) { if (g->start == 0) return -1; g->end = g->start - 1; for (g->start = g->end; xdf->rchg[g->start - 1]; g->start--) ; return 0; } /* * If g can be slid toward the end of the file, do so, and if it bumps into a * following group, expand this group to include it. Return 0 on success or -1 * if g cannot be slid down. */ static int group_slide_down(xdfile_t *xdf, struct xdlgroup *g, long flags) { if (g->end < xdf->nrec && recs_match(xdf->recs[g->start], xdf->recs[g->end], flags)) { xdf->rchg[g->start++] = 0; xdf->rchg[g->end++] = 1; while (xdf->rchg[g->end]) g->end++; return 0; } else { return -1; } } /* * If g can be slid toward the beginning of the file, do so, and if it bumps * into a previous group, expand this group to include it. Return 0 on success * or -1 if g cannot be slid up. */ static int group_slide_up(xdfile_t *xdf, struct xdlgroup *g, long flags) { if (g->start > 0 && recs_match(xdf->recs[g->start - 1], xdf->recs[g->end - 1], flags)) { xdf->rchg[--g->start] = 1; xdf->rchg[--g->end] = 0; while (xdf->rchg[g->start - 1]) g->start--; return 0; } else { return -1; } } static void xdl_bug(const char *msg) { fprintf(stderr, "BUG: %s\n", msg); exit(1); } /* * Move back and forward change groups for a consistent and pretty diff output. * This also helps in finding joinable change groups and reducing the diff * size. */ int xdl_change_compact(xdfile_t *xdf, xdfile_t *xdfo, long flags) { struct xdlgroup g, go; long earliest_end, end_matching_other; long groupsize; group_init(xdf, &g); group_init(xdfo, &go); while (1) { /* If the group is empty in the to-be-compacted file, skip it: */ if (g.end == g.start) goto next; /* * Now shift the change up and then down as far as possible in * each direction. If it bumps into any other changes, merge them. */ do { groupsize = g.end - g.start; /* * Keep track of the last "end" index that causes this * group to align with a group of changed lines in the * other file. -1 indicates that we haven't found such * a match yet: */ end_matching_other = -1; /* Shift the group backward as much as possible: */ while (!group_slide_up(xdf, &g, flags)) if (group_previous(xdfo, &go)) xdl_bug("group sync broken sliding up"); /* * This is this highest that this group can be shifted. * Record its end index: */ earliest_end = g.end; if (go.end > go.start) end_matching_other = g.end; /* Now shift the group forward as far as possible: */ while (1) { if (group_slide_down(xdf, &g, flags)) break; if (group_next(xdfo, &go)) xdl_bug("group sync broken sliding down"); if (go.end > go.start) end_matching_other = g.end; } } while (groupsize != g.end - g.start); /* * If the group can be shifted, then we can possibly use this * freedom to produce a more intuitive diff. * * The group is currently shifted as far down as possible, so the * heuristics below only have to handle upwards shifts. */ if (g.end == earliest_end) { /* no shifting was possible */ } else if (end_matching_other != -1) { /* * Move the possibly merged group of changes back to line * up with the last group of changes from the other file * that it can align with. */ while (go.end == go.start) { if (group_slide_up(xdf, &g, flags)) xdl_bug("match disappeared"); if (group_previous(xdfo, &go)) xdl_bug("group sync broken sliding to match"); } } else if (flags & XDF_INDENT_HEURISTIC) { /* * Indent heuristic: a group of pure add/delete lines * implies two splits, one between the end of the "before" * context and the start of the group, and another between * the end of the group and the beginning of the "after" * context. Some splits are aesthetically better and some * are worse. We compute a badness "score" for each split, * and add the scores for the two splits to define a * "score" for each position that the group can be shifted * to. Then we pick the shift with the lowest score. */ long shift, best_shift = -1; struct split_score best_score; for (shift = earliest_end; shift <= g.end; shift++) { struct split_measurement m; struct split_score score = {0, 0}; measure_split(xdf, shift, &m); score_add_split(&m, &score); measure_split(xdf, shift - groupsize, &m); score_add_split(&m, &score); if (best_shift == -1 || score_cmp(&score, &best_score) <= 0) { best_score.effective_indent = score.effective_indent; best_score.penalty = score.penalty; best_shift = shift; } } while (g.end > best_shift) { if (group_slide_up(xdf, &g, flags)) xdl_bug("best shift unreached"); if (group_previous(xdfo, &go)) xdl_bug("group sync broken sliding to blank line"); } } next: /* Move past the just-processed group: */ if (group_next(xdf, &g)) break; if (group_next(xdfo, &go)) xdl_bug("group sync broken moving to next group"); } if (!group_next(xdfo, &go)) xdl_bug("group sync broken at end of file"); return 0; } int xdl_build_script(xdfenv_t *xe, xdchange_t **xscr) { xdchange_t *cscr = NULL, *xch; char *rchg1 = xe->xdf1.rchg, *rchg2 = xe->xdf2.rchg; long i1, i2, l1, l2; /* * Trivial. Collects "groups" of changes and creates an edit script. */ for (i1 = xe->xdf1.nrec, i2 = xe->xdf2.nrec; i1 >= 0 || i2 >= 0; i1--, i2--) if (rchg1[i1 - 1] || rchg2[i2 - 1]) { for (l1 = i1; rchg1[i1 - 1]; i1--); for (l2 = i2; rchg2[i2 - 1]; i2--); if (!(xch = xdl_add_change(cscr, i1, i2, l1 - i1, l2 - i2))) { xdl_free_script(cscr); return -1; } cscr = xch; } *xscr = cscr; return 0; } void xdl_free_script(xdchange_t *xscr) { xdchange_t *xch; while ((xch = xscr) != NULL) { xscr = xscr->next; xdl_free(xch); } } static int xdl_call_hunk_func(xdfenv_t *xe, xdchange_t *xscr, xdemitcb_t *ecb, xdemitconf_t const *xecfg) { xdchange_t *xch, *xche; (void)xe; for (xch = xscr; xch; xch = xche->next) { xche = xdl_get_hunk(&xch, xecfg); if (!xch) break; if (xecfg->hunk_func(xch->i1, xche->i1 + xche->chg1 - xch->i1, xch->i2, xche->i2 + xche->chg2 - xch->i2, ecb->priv) < 0) return -1; } return 0; } static void xdl_mark_ignorable(xdchange_t *xscr, xdfenv_t *xe, long flags) { xdchange_t *xch; for (xch = xscr; xch; xch = xch->next) { int ignore = 1; xrecord_t **rec; long i; rec = &xe->xdf1.recs[xch->i1]; for (i = 0; i < xch->chg1 && ignore; i++) ignore = xdl_blankline(rec[i]->ptr, rec[i]->size, flags); rec = &xe->xdf2.recs[xch->i2]; for (i = 0; i < xch->chg2 && ignore; i++) ignore = xdl_blankline(rec[i]->ptr, rec[i]->size, flags); xch->ignore = ignore; } } int xdl_diff(mmfile_t *mf1, mmfile_t *mf2, xpparam_t const *xpp, xdemitconf_t const *xecfg, xdemitcb_t *ecb) { xdchange_t *xscr; xdfenv_t xe; emit_func_t ef = xecfg->hunk_func ? xdl_call_hunk_func : xdl_emit_diff; if (xdl_do_diff(mf1, mf2, xpp, &xe) < 0) { return -1; } if (xdl_change_compact(&xe.xdf1, &xe.xdf2, xpp->flags) < 0 || xdl_change_compact(&xe.xdf2, &xe.xdf1, xpp->flags) < 0 || xdl_build_script(&xe, &xscr) < 0) { xdl_free_env(&xe); return -1; } if (xscr) { if (xpp->flags & XDF_IGNORE_BLANK_LINES) xdl_mark_ignorable(xscr, &xe, xpp->flags); if (ef(&xe, xscr, ecb, xecfg) < 0) { xdl_free_script(xscr); xdl_free_env(&xe); return -1; } xdl_free_script(xscr); } xdl_free_env(&xe); return 0; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/xdiff/xemit.c
/* * LibXDiff by Davide Libenzi ( File Differential Library ) * Copyright (C) 2003 Davide Libenzi * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see * <http://www.gnu.org/licenses/>. * * Davide Libenzi <[email protected]> * */ #include "xinclude.h" static long xdl_get_rec(xdfile_t *xdf, long ri, char const **rec) { *rec = xdf->recs[ri]->ptr; return xdf->recs[ri]->size; } static int xdl_emit_record(xdfile_t *xdf, long ri, char const *pre, xdemitcb_t *ecb) { long size, psize = (long)strlen(pre); char const *rec; size = xdl_get_rec(xdf, ri, &rec); if (xdl_emit_diffrec(rec, size, pre, psize, ecb) < 0) { return -1; } return 0; } /* * Starting at the passed change atom, find the latest change atom to be included * inside the differential hunk according to the specified configuration. * Also advance xscr if the first changes must be discarded. */ xdchange_t *xdl_get_hunk(xdchange_t **xscr, xdemitconf_t const *xecfg) { xdchange_t *xch, *xchp, *lxch; long max_common = 2 * xecfg->ctxlen + xecfg->interhunkctxlen; long max_ignorable = xecfg->ctxlen; unsigned long ignored = 0; /* number of ignored blank lines */ /* remove ignorable changes that are too far before other changes */ for (xchp = *xscr; xchp && xchp->ignore; xchp = xchp->next) { xch = xchp->next; if (xch == NULL || xch->i1 - (xchp->i1 + xchp->chg1) >= max_ignorable) *xscr = xch; } if (*xscr == NULL) return NULL; lxch = *xscr; for (xchp = *xscr, xch = xchp->next; xch; xchp = xch, xch = xch->next) { long distance = xch->i1 - (xchp->i1 + xchp->chg1); if (distance > max_common) break; if (distance < max_ignorable && (!xch->ignore || lxch == xchp)) { lxch = xch; ignored = 0; } else if (distance < max_ignorable && xch->ignore) { ignored += xch->chg2; } else if (lxch != xchp && xch->i1 + ignored - (lxch->i1 + lxch->chg1) > (unsigned long)max_common) { break; } else if (!xch->ignore) { lxch = xch; ignored = 0; } else { ignored += xch->chg2; } } return lxch; } static long def_ff(const char *rec, long len, char *buf, long sz, void *priv) { (void)priv; if (len > 0 && (isalpha((unsigned char)*rec) || /* identifier? */ *rec == '_' || /* also identifier? */ *rec == '$')) { /* identifiers from VMS and other esoterico */ if (len > sz) len = sz; while (0 < len && isspace((unsigned char)rec[len - 1])) len--; memcpy(buf, rec, len); return len; } return -1; } static long match_func_rec(xdfile_t *xdf, xdemitconf_t const *xecfg, long ri, char *buf, long sz) { const char *rec; long len = xdl_get_rec(xdf, ri, &rec); if (!xecfg->find_func) return def_ff(rec, len, buf, sz, xecfg->find_func_priv); return xecfg->find_func(rec, len, buf, sz, xecfg->find_func_priv); } static int is_func_rec(xdfile_t *xdf, xdemitconf_t const *xecfg, long ri) { char dummy[1]; return match_func_rec(xdf, xecfg, ri, dummy, sizeof(dummy)) >= 0; } struct func_line { long len; char buf[80]; }; static long get_func_line(xdfenv_t *xe, xdemitconf_t const *xecfg, struct func_line *func_line, long start, long limit) { long l, size, step = (start > limit) ? -1 : 1; char *buf, dummy[1]; buf = func_line ? func_line->buf : dummy; size = func_line ? sizeof(func_line->buf) : sizeof(dummy); for (l = start; l != limit && 0 <= l && l < xe->xdf1.nrec; l += step) { long len = match_func_rec(&xe->xdf1, xecfg, l, buf, size); if (len >= 0) { if (func_line) func_line->len = len; return l; } } return -1; } static int is_empty_rec(xdfile_t *xdf, long ri) { const char *rec; long len = xdl_get_rec(xdf, ri, &rec); while (len > 0 && XDL_ISSPACE(*rec)) { rec++; len--; } return !len; } int xdl_emit_diff(xdfenv_t *xe, xdchange_t *xscr, xdemitcb_t *ecb, xdemitconf_t const *xecfg) { long s1, s2, e1, e2, lctx; xdchange_t *xch, *xche; long funclineprev = -1; struct func_line func_line = { 0 }; for (xch = xscr; xch; xch = xche->next) { xche = xdl_get_hunk(&xch, xecfg); if (!xch) break; s1 = XDL_MAX(xch->i1 - xecfg->ctxlen, 0); s2 = XDL_MAX(xch->i2 - xecfg->ctxlen, 0); if (xecfg->flags & XDL_EMIT_FUNCCONTEXT) { long fs1, i1 = xch->i1; /* Appended chunk? */ if (i1 >= xe->xdf1.nrec) { long i2 = xch->i2; /* * We don't need additional context if * a whole function was added. */ while (i2 < xe->xdf2.nrec) { if (is_func_rec(&xe->xdf2, xecfg, i2)) goto post_context_calculation; i2++; } /* * Otherwise get more context from the * pre-image. */ i1 = xe->xdf1.nrec - 1; } fs1 = get_func_line(xe, xecfg, NULL, i1, -1); while (fs1 > 0 && !is_empty_rec(&xe->xdf1, fs1 - 1) && !is_func_rec(&xe->xdf1, xecfg, fs1 - 1)) fs1--; if (fs1 < 0) fs1 = 0; if (fs1 < s1) { s2 -= s1 - fs1; s1 = fs1; } } post_context_calculation: lctx = xecfg->ctxlen; lctx = XDL_MIN(lctx, xe->xdf1.nrec - (xche->i1 + xche->chg1)); lctx = XDL_MIN(lctx, xe->xdf2.nrec - (xche->i2 + xche->chg2)); e1 = xche->i1 + xche->chg1 + lctx; e2 = xche->i2 + xche->chg2 + lctx; if (xecfg->flags & XDL_EMIT_FUNCCONTEXT) { long fe1 = get_func_line(xe, xecfg, NULL, xche->i1 + xche->chg1, xe->xdf1.nrec); while (fe1 > 0 && is_empty_rec(&xe->xdf1, fe1 - 1)) fe1--; if (fe1 < 0) fe1 = xe->xdf1.nrec; if (fe1 > e1) { e2 += fe1 - e1; e1 = fe1; } /* * Overlap with next change? Then include it * in the current hunk and start over to find * its new end. */ if (xche->next) { long l = XDL_MIN(xche->next->i1, xe->xdf1.nrec - 1); if (l - xecfg->ctxlen <= e1 || get_func_line(xe, xecfg, NULL, l, e1) < 0) { xche = xche->next; goto post_context_calculation; } } } /* * Emit current hunk header. */ if (xecfg->flags & XDL_EMIT_FUNCNAMES) { get_func_line(xe, xecfg, &func_line, s1 - 1, funclineprev); funclineprev = s1 - 1; } if (xdl_emit_hunk_hdr(s1 + 1, e1 - s1, s2 + 1, e2 - s2, func_line.buf, func_line.len, ecb) < 0) return -1; /* * Emit pre-context. */ for (; s2 < xch->i2; s2++) if (xdl_emit_record(&xe->xdf2, s2, " ", ecb) < 0) return -1; for (s1 = xch->i1, s2 = xch->i2;; xch = xch->next) { /* * Merge previous with current change atom. */ for (; s1 < xch->i1 && s2 < xch->i2; s1++, s2++) if (xdl_emit_record(&xe->xdf2, s2, " ", ecb) < 0) return -1; /* * Removes lines from the first file. */ for (s1 = xch->i1; s1 < xch->i1 + xch->chg1; s1++) if (xdl_emit_record(&xe->xdf1, s1, "-", ecb) < 0) return -1; /* * Adds lines from the second file. */ for (s2 = xch->i2; s2 < xch->i2 + xch->chg2; s2++) if (xdl_emit_record(&xe->xdf2, s2, "+", ecb) < 0) return -1; if (xch == xche) break; s1 = xch->i1 + xch->chg1; s2 = xch->i2 + xch->chg2; } /* * Emit post-context. */ for (s2 = xche->i2 + xche->chg2; s2 < e2; s2++) if (xdl_emit_record(&xe->xdf2, s2, " ", ecb) < 0) return -1; } return 0; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/transports/auth_negotiate.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "auth_negotiate.h" #if defined(GIT_GSSAPI) || defined(GIT_GSSFRAMEWORK) #include "git2.h" #include "buffer.h" #include "auth.h" #include "git2/sys/credential.h" #ifdef GIT_GSSFRAMEWORK #import <GSS/GSS.h> #elif defined(GIT_GSSAPI) #include <gssapi.h> #include <krb5.h> #endif static gss_OID_desc negotiate_oid_spnego = { 6, (void *) "\x2b\x06\x01\x05\x05\x02" }; static gss_OID_desc negotiate_oid_krb5 = { 9, (void *) "\x2a\x86\x48\x86\xf7\x12\x01\x02\x02" }; static gss_OID negotiate_oids[] = { &negotiate_oid_spnego, &negotiate_oid_krb5, NULL }; typedef struct { git_http_auth_context parent; unsigned configured : 1, complete : 1; git_buf target; char *challenge; gss_ctx_id_t gss_context; gss_OID oid; } http_auth_negotiate_context; static void negotiate_err_set( OM_uint32 status_major, OM_uint32 status_minor, const char *message) { gss_buffer_desc buffer = GSS_C_EMPTY_BUFFER; OM_uint32 status_display, context = 0; if (gss_display_status(&status_display, status_major, GSS_C_GSS_CODE, GSS_C_NO_OID, &context, &buffer) == GSS_S_COMPLETE) { git_error_set(GIT_ERROR_NET, "%s: %.*s (%d.%d)", message, (int)buffer.length, (const char *)buffer.value, status_major, status_minor); gss_release_buffer(&status_minor, &buffer); } else { git_error_set(GIT_ERROR_NET, "%s: unknown negotiate error (%d.%d)", message, status_major, status_minor); } } static int negotiate_set_challenge( git_http_auth_context *c, const char *challenge) { http_auth_negotiate_context *ctx = (http_auth_negotiate_context *)c; GIT_ASSERT_ARG(ctx); GIT_ASSERT_ARG(challenge); GIT_ASSERT(ctx->configured); git__free(ctx->challenge); ctx->challenge = git__strdup(challenge); GIT_ERROR_CHECK_ALLOC(ctx->challenge); return 0; } static void negotiate_context_dispose(http_auth_negotiate_context *ctx) { OM_uint32 status_minor; if (ctx->gss_context != GSS_C_NO_CONTEXT) { gss_delete_sec_context( &status_minor, &ctx->gss_context, GSS_C_NO_BUFFER); ctx->gss_context = GSS_C_NO_CONTEXT; } git_buf_dispose(&ctx->target); git__free(ctx->challenge); ctx->challenge = NULL; } static int negotiate_next_token( git_buf *buf, git_http_auth_context *c, git_credential *cred) { http_auth_negotiate_context *ctx = (http_auth_negotiate_context *)c; OM_uint32 status_major, status_minor; gss_buffer_desc target_buffer = GSS_C_EMPTY_BUFFER, input_token = GSS_C_EMPTY_BUFFER, output_token = GSS_C_EMPTY_BUFFER; gss_buffer_t input_token_ptr = GSS_C_NO_BUFFER; git_buf input_buf = GIT_BUF_INIT; gss_name_t server = NULL; gss_OID mech; size_t challenge_len; int error = 0; GIT_ASSERT_ARG(buf); GIT_ASSERT_ARG(ctx); GIT_ASSERT_ARG(cred); GIT_ASSERT(ctx->configured); GIT_ASSERT(cred->credtype == GIT_CREDENTIAL_DEFAULT); if (ctx->complete) return 0; target_buffer.value = (void *)ctx->target.ptr; target_buffer.length = ctx->target.size; status_major = gss_import_name(&status_minor, &target_buffer, GSS_C_NT_HOSTBASED_SERVICE, &server); if (GSS_ERROR(status_major)) { negotiate_err_set(status_major, status_minor, "could not parse principal"); error = -1; goto done; } challenge_len = ctx->challenge ? strlen(ctx->challenge) : 0; if (challenge_len < 9 || memcmp(ctx->challenge, "Negotiate", 9) != 0) { git_error_set(GIT_ERROR_NET, "server did not request negotiate"); error = -1; goto done; } if (challenge_len > 9) { if (git_buf_decode_base64(&input_buf, ctx->challenge + 10, challenge_len - 10) < 0) { git_error_set(GIT_ERROR_NET, "invalid negotiate challenge from server"); error = -1; goto done; } input_token.value = input_buf.ptr; input_token.length = input_buf.size; input_token_ptr = &input_token; } else if (ctx->gss_context != GSS_C_NO_CONTEXT) { negotiate_context_dispose(ctx); } mech = &negotiate_oid_spnego; status_major = gss_init_sec_context( &status_minor, GSS_C_NO_CREDENTIAL, &ctx->gss_context, server, mech, GSS_C_DELEG_FLAG | GSS_C_MUTUAL_FLAG, GSS_C_INDEFINITE, GSS_C_NO_CHANNEL_BINDINGS, input_token_ptr, NULL, &output_token, NULL, NULL); if (GSS_ERROR(status_major)) { negotiate_err_set(status_major, status_minor, "negotiate failure"); error = -1; goto done; } /* This message merely told us auth was complete; we do not respond. */ if (status_major == GSS_S_COMPLETE) { negotiate_context_dispose(ctx); ctx->complete = 1; goto done; } if (output_token.length == 0) { git_error_set(GIT_ERROR_NET, "GSSAPI did not return token"); error = -1; goto done; } git_buf_puts(buf, "Negotiate "); git_buf_encode_base64(buf, output_token.value, output_token.length); if (git_buf_oom(buf)) error = -1; done: gss_release_name(&status_minor, &server); gss_release_buffer(&status_minor, (gss_buffer_t) &output_token); git_buf_dispose(&input_buf); return error; } static int negotiate_is_complete(git_http_auth_context *c) { http_auth_negotiate_context *ctx = (http_auth_negotiate_context *)c; GIT_ASSERT_ARG(ctx); return (ctx->complete == 1); } static void negotiate_context_free(git_http_auth_context *c) { http_auth_negotiate_context *ctx = (http_auth_negotiate_context *)c; negotiate_context_dispose(ctx); ctx->configured = 0; ctx->complete = 0; ctx->oid = NULL; git__free(ctx); } static int negotiate_init_context( http_auth_negotiate_context *ctx, const git_net_url *url) { OM_uint32 status_major, status_minor; gss_OID item, *oid; gss_OID_set mechanism_list; size_t i; /* Query supported mechanisms looking for SPNEGO) */ status_major = gss_indicate_mechs(&status_minor, &mechanism_list); if (GSS_ERROR(status_major)) { negotiate_err_set(status_major, status_minor, "could not query mechanisms"); return -1; } if (mechanism_list) { for (oid = negotiate_oids; *oid; oid++) { for (i = 0; i < mechanism_list->count; i++) { item = &mechanism_list->elements[i]; if (item->length == (*oid)->length && memcmp(item->elements, (*oid)->elements, item->length) == 0) { ctx->oid = *oid; break; } } if (ctx->oid) break; } } gss_release_oid_set(&status_minor, &mechanism_list); if (!ctx->oid) { git_error_set(GIT_ERROR_NET, "negotiate authentication is not supported"); return GIT_EAUTH; } git_buf_puts(&ctx->target, "HTTP@"); git_buf_puts(&ctx->target, url->host); if (git_buf_oom(&ctx->target)) return -1; ctx->gss_context = GSS_C_NO_CONTEXT; ctx->configured = 1; return 0; } int git_http_auth_negotiate( git_http_auth_context **out, const git_net_url *url) { http_auth_negotiate_context *ctx; *out = NULL; ctx = git__calloc(1, sizeof(http_auth_negotiate_context)); GIT_ERROR_CHECK_ALLOC(ctx); if (negotiate_init_context(ctx, url) < 0) { git__free(ctx); return -1; } ctx->parent.type = GIT_HTTP_AUTH_NEGOTIATE; ctx->parent.credtypes = GIT_CREDENTIAL_DEFAULT; ctx->parent.connection_affinity = 1; ctx->parent.set_challenge = negotiate_set_challenge; ctx->parent.next_token = negotiate_next_token; ctx->parent.is_complete = negotiate_is_complete; ctx->parent.free = negotiate_context_free; *out = (git_http_auth_context *)ctx; return 0; } #endif /* GIT_GSSAPI */
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/transports/winhttp.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "common.h" #ifdef GIT_WINHTTP #include "git2.h" #include "git2/transport.h" #include "buffer.h" #include "posix.h" #include "netops.h" #include "smart.h" #include "remote.h" #include "repository.h" #include "http.h" #include "git2/sys/credential.h" #include <wincrypt.h> #include <winhttp.h> /* For IInternetSecurityManager zone check */ #include <objbase.h> #include <urlmon.h> #define WIDEN2(s) L ## s #define WIDEN(s) WIDEN2(s) #define MAX_CONTENT_TYPE_LEN 100 #define WINHTTP_OPTION_PEERDIST_EXTENSION_STATE 109 #define CACHED_POST_BODY_BUF_SIZE 4096 #define UUID_LENGTH_CCH 32 #define TIMEOUT_INFINITE -1 #define DEFAULT_CONNECT_TIMEOUT 60000 #ifndef WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH #define WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH 0 #endif #ifndef WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 # define WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 0x00000200 #endif #ifndef WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 # define WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 0x00000800 #endif #ifndef WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3 # define WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3 0x00002000 #endif #ifndef WINHTTP_NO_CLIENT_CERT_CONTEXT # define WINHTTP_NO_CLIENT_CERT_CONTEXT NULL #endif #ifndef HTTP_STATUS_PERMANENT_REDIRECT # define HTTP_STATUS_PERMANENT_REDIRECT 308 #endif #ifndef DWORD_MAX # define DWORD_MAX 0xffffffff #endif bool git_http__expect_continue = false; static const char *prefix_https = "https://"; static const char *upload_pack_service = "upload-pack"; static const char *upload_pack_ls_service_url = "/info/refs?service=git-upload-pack"; static const char *upload_pack_service_url = "/git-upload-pack"; static const char *receive_pack_service = "receive-pack"; static const char *receive_pack_ls_service_url = "/info/refs?service=git-receive-pack"; static const char *receive_pack_service_url = "/git-receive-pack"; static const wchar_t *get_verb = L"GET"; static const wchar_t *post_verb = L"POST"; static const wchar_t *pragma_nocache = L"Pragma: no-cache"; static const wchar_t *transfer_encoding = L"Transfer-Encoding: chunked"; static const int no_check_cert_flags = SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID | SECURITY_FLAG_IGNORE_UNKNOWN_CA; #if defined(__MINGW32__) static const CLSID CLSID_InternetSecurityManager_mingw = { 0x7B8A2D94, 0x0AC9, 0x11D1, { 0x89, 0x6C, 0x00, 0xC0, 0x4F, 0xB6, 0xBF, 0xC4 } }; static const IID IID_IInternetSecurityManager_mingw = { 0x79EAC9EE, 0xBAF9, 0x11CE, { 0x8C, 0x82, 0x00, 0xAA, 0x00, 0x4B, 0xA9, 0x0B } }; # define CLSID_InternetSecurityManager CLSID_InternetSecurityManager_mingw # define IID_IInternetSecurityManager IID_IInternetSecurityManager_mingw #endif #define OWNING_SUBTRANSPORT(s) ((winhttp_subtransport *)(s)->parent.subtransport) typedef enum { GIT_WINHTTP_AUTH_BASIC = 1, GIT_WINHTTP_AUTH_NTLM = 2, GIT_WINHTTP_AUTH_NEGOTIATE = 4, GIT_WINHTTP_AUTH_DIGEST = 8, } winhttp_authmechanism_t; typedef struct { git_smart_subtransport_stream parent; const char *service; const char *service_url; const wchar_t *verb; HINTERNET request; wchar_t *request_uri; char *chunk_buffer; unsigned chunk_buffer_len; HANDLE post_body; DWORD post_body_len; unsigned sent_request : 1, received_response : 1, chunked : 1, status_sending_request_reached: 1; } winhttp_stream; typedef struct { git_net_url url; git_credential *cred; int auth_mechanisms; bool url_cred_presented; } winhttp_server; typedef struct { git_smart_subtransport parent; transport_smart *owner; winhttp_server server; winhttp_server proxy; HINTERNET session; HINTERNET connection; } winhttp_subtransport; static int apply_userpass_credentials(HINTERNET request, DWORD target, int mechanisms, git_credential *cred) { git_credential_userpass_plaintext *c = (git_credential_userpass_plaintext *)cred; wchar_t *user = NULL, *pass = NULL; int user_len = 0, pass_len = 0, error = 0; DWORD native_scheme; if (mechanisms & GIT_WINHTTP_AUTH_NEGOTIATE) { native_scheme = WINHTTP_AUTH_SCHEME_NEGOTIATE; } else if (mechanisms & GIT_WINHTTP_AUTH_NTLM) { native_scheme = WINHTTP_AUTH_SCHEME_NTLM; } else if (mechanisms & GIT_WINHTTP_AUTH_DIGEST) { native_scheme = WINHTTP_AUTH_SCHEME_DIGEST; } else if (mechanisms & GIT_WINHTTP_AUTH_BASIC) { native_scheme = WINHTTP_AUTH_SCHEME_BASIC; } else { git_error_set(GIT_ERROR_HTTP, "invalid authentication scheme"); error = GIT_EAUTH; goto done; } if ((error = user_len = git__utf8_to_16_alloc(&user, c->username)) < 0) goto done; if ((error = pass_len = git__utf8_to_16_alloc(&pass, c->password)) < 0) goto done; if (!WinHttpSetCredentials(request, target, native_scheme, user, pass, NULL)) { git_error_set(GIT_ERROR_OS, "failed to set credentials"); error = -1; } done: if (user_len > 0) git__memzero(user, user_len * sizeof(wchar_t)); if (pass_len > 0) git__memzero(pass, pass_len * sizeof(wchar_t)); git__free(user); git__free(pass); return error; } static int apply_default_credentials(HINTERNET request, DWORD target, int mechanisms) { DWORD autologon_level = WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW; DWORD native_scheme = 0; if ((mechanisms & GIT_WINHTTP_AUTH_NEGOTIATE) != 0) { native_scheme = WINHTTP_AUTH_SCHEME_NEGOTIATE; } else if ((mechanisms & GIT_WINHTTP_AUTH_NTLM) != 0) { native_scheme = WINHTTP_AUTH_SCHEME_NTLM; } else { git_error_set(GIT_ERROR_HTTP, "invalid authentication scheme"); return GIT_EAUTH; } /* * Autologon policy must be "low" to use default creds. * This is safe as the user has explicitly requested it. */ if (!WinHttpSetOption(request, WINHTTP_OPTION_AUTOLOGON_POLICY, &autologon_level, sizeof(DWORD))) { git_error_set(GIT_ERROR_OS, "could not configure logon policy"); return -1; } if (!WinHttpSetCredentials(request, target, native_scheme, NULL, NULL, NULL)) { git_error_set(GIT_ERROR_OS, "could not configure credentials"); return -1; } return 0; } static int acquire_url_cred( git_credential **cred, unsigned int allowed_types, const char *username, const char *password) { if (allowed_types & GIT_CREDENTIAL_USERPASS_PLAINTEXT) return git_credential_userpass_plaintext_new(cred, username, password); if ((allowed_types & GIT_CREDENTIAL_DEFAULT) && *username == '\0' && *password == '\0') return git_credential_default_new(cred); return 1; } static int acquire_fallback_cred( git_credential **cred, const char *url, unsigned int allowed_types) { int error = 1; /* If the target URI supports integrated Windows authentication * as an authentication mechanism */ if (GIT_CREDENTIAL_DEFAULT & allowed_types) { wchar_t *wide_url; HRESULT hCoInitResult; /* Convert URL to wide characters */ if (git__utf8_to_16_alloc(&wide_url, url) < 0) { git_error_set(GIT_ERROR_OS, "failed to convert string to wide form"); return -1; } hCoInitResult = CoInitializeEx(NULL, COINIT_MULTITHREADED); if (SUCCEEDED(hCoInitResult) || hCoInitResult == RPC_E_CHANGED_MODE) { IInternetSecurityManager *pISM; /* And if the target URI is in the My Computer, Intranet, or Trusted zones */ if (SUCCEEDED(CoCreateInstance(&CLSID_InternetSecurityManager, NULL, CLSCTX_ALL, &IID_IInternetSecurityManager, (void **)&pISM))) { DWORD dwZone; if (SUCCEEDED(pISM->lpVtbl->MapUrlToZone(pISM, wide_url, &dwZone, 0)) && (URLZONE_LOCAL_MACHINE == dwZone || URLZONE_INTRANET == dwZone || URLZONE_TRUSTED == dwZone)) { git_credential *existing = *cred; if (existing) existing->free(existing); /* Then use default Windows credentials to authenticate this request */ error = git_credential_default_new(cred); } pISM->lpVtbl->Release(pISM); } /* Only uninitialize if the call to CoInitializeEx was successful. */ if (SUCCEEDED(hCoInitResult)) CoUninitialize(); } git__free(wide_url); } return error; } static int certificate_check(winhttp_stream *s, int valid) { int error; winhttp_subtransport *t = OWNING_SUBTRANSPORT(s); PCERT_CONTEXT cert_ctx; DWORD cert_ctx_size = sizeof(cert_ctx); git_cert_x509 cert; /* If there is no override, we should fail if WinHTTP doesn't think it's fine */ if (t->owner->certificate_check_cb == NULL && !valid) { if (!git_error_last()) git_error_set(GIT_ERROR_HTTP, "unknown certificate check failure"); return GIT_ECERTIFICATE; } if (t->owner->certificate_check_cb == NULL || git__strcmp(t->server.url.scheme, "https") != 0) return 0; if (!WinHttpQueryOption(s->request, WINHTTP_OPTION_SERVER_CERT_CONTEXT, &cert_ctx, &cert_ctx_size)) { git_error_set(GIT_ERROR_OS, "failed to get server certificate"); return -1; } git_error_clear(); cert.parent.cert_type = GIT_CERT_X509; cert.data = cert_ctx->pbCertEncoded; cert.len = cert_ctx->cbCertEncoded; error = t->owner->certificate_check_cb((git_cert *) &cert, valid, t->server.url.host, t->owner->message_cb_payload); CertFreeCertificateContext(cert_ctx); if (error == GIT_PASSTHROUGH) error = valid ? 0 : GIT_ECERTIFICATE; if (error < 0 && !git_error_last()) git_error_set(GIT_ERROR_HTTP, "user cancelled certificate check"); return error; } static void winhttp_stream_close(winhttp_stream *s) { if (s->chunk_buffer) { git__free(s->chunk_buffer); s->chunk_buffer = NULL; } if (s->post_body) { CloseHandle(s->post_body); s->post_body = NULL; } if (s->request_uri) { git__free(s->request_uri); s->request_uri = NULL; } if (s->request) { WinHttpCloseHandle(s->request); s->request = NULL; } s->sent_request = 0; } static int apply_credentials( HINTERNET request, git_net_url *url, int target, git_credential *creds, int mechanisms) { int error = 0; GIT_UNUSED(url); /* If we have creds, just apply them */ if (creds && creds->credtype == GIT_CREDENTIAL_USERPASS_PLAINTEXT) error = apply_userpass_credentials(request, target, mechanisms, creds); else if (creds && creds->credtype == GIT_CREDENTIAL_DEFAULT) error = apply_default_credentials(request, target, mechanisms); return error; } static int winhttp_stream_connect(winhttp_stream *s) { winhttp_subtransport *t = OWNING_SUBTRANSPORT(s); git_buf buf = GIT_BUF_INIT; char *proxy_url = NULL; wchar_t ct[MAX_CONTENT_TYPE_LEN]; LPCWSTR types[] = { L"*/*", NULL }; BOOL peerdist = FALSE; int error = -1; unsigned long disable_redirects = WINHTTP_DISABLE_REDIRECTS; int default_timeout = TIMEOUT_INFINITE; int default_connect_timeout = DEFAULT_CONNECT_TIMEOUT; DWORD autologon_policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH; const char *service_url = s->service_url; size_t i; const git_proxy_options *proxy_opts; /* If path already ends in /, remove the leading slash from service_url */ if ((git__suffixcmp(t->server.url.path, "/") == 0) && (git__prefixcmp(service_url, "/") == 0)) service_url++; /* Prepare URL */ git_buf_printf(&buf, "%s%s", t->server.url.path, service_url); if (git_buf_oom(&buf)) return -1; /* Convert URL to wide characters */ if (git__utf8_to_16_alloc(&s->request_uri, git_buf_cstr(&buf)) < 0) { git_error_set(GIT_ERROR_OS, "failed to convert string to wide form"); goto on_error; } /* Establish request */ s->request = WinHttpOpenRequest( t->connection, s->verb, s->request_uri, NULL, WINHTTP_NO_REFERER, types, git__strcmp(t->server.url.scheme, "https") == 0 ? WINHTTP_FLAG_SECURE : 0); if (!s->request) { git_error_set(GIT_ERROR_OS, "failed to open request"); goto on_error; } /* Never attempt default credentials; we'll provide them explicitly. */ if (!WinHttpSetOption(s->request, WINHTTP_OPTION_AUTOLOGON_POLICY, &autologon_policy, sizeof(DWORD))) return -1; if (!WinHttpSetTimeouts(s->request, default_timeout, default_connect_timeout, default_timeout, default_timeout)) { git_error_set(GIT_ERROR_OS, "failed to set timeouts for WinHTTP"); goto on_error; } proxy_opts = &t->owner->proxy; if (proxy_opts->type == GIT_PROXY_AUTO) { /* Set proxy if necessary */ if (git_remote__http_proxy(&proxy_url, t->owner->owner, &t->server.url) < 0) goto on_error; } else if (proxy_opts->type == GIT_PROXY_SPECIFIED) { proxy_url = git__strdup(proxy_opts->url); GIT_ERROR_CHECK_ALLOC(proxy_url); } if (proxy_url) { git_buf processed_url = GIT_BUF_INIT; WINHTTP_PROXY_INFO proxy_info; wchar_t *proxy_wide; git_net_url_dispose(&t->proxy.url); if ((error = git_net_url_parse(&t->proxy.url, proxy_url)) < 0) goto on_error; if (strcmp(t->proxy.url.scheme, "http") != 0 && strcmp(t->proxy.url.scheme, "https") != 0) { git_error_set(GIT_ERROR_HTTP, "invalid URL: '%s'", proxy_url); error = -1; goto on_error; } git_buf_puts(&processed_url, t->proxy.url.scheme); git_buf_PUTS(&processed_url, "://"); if (git_net_url_is_ipv6(&t->proxy.url)) git_buf_putc(&processed_url, '['); git_buf_puts(&processed_url, t->proxy.url.host); if (git_net_url_is_ipv6(&t->proxy.url)) git_buf_putc(&processed_url, ']'); if (!git_net_url_is_default_port(&t->proxy.url)) git_buf_printf(&processed_url, ":%s", t->proxy.url.port); if (git_buf_oom(&processed_url)) { error = -1; goto on_error; } /* Convert URL to wide characters */ error = git__utf8_to_16_alloc(&proxy_wide, processed_url.ptr); git_buf_dispose(&processed_url); if (error < 0) goto on_error; proxy_info.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY; proxy_info.lpszProxy = proxy_wide; proxy_info.lpszProxyBypass = NULL; if (!WinHttpSetOption(s->request, WINHTTP_OPTION_PROXY, &proxy_info, sizeof(WINHTTP_PROXY_INFO))) { git_error_set(GIT_ERROR_OS, "failed to set proxy"); git__free(proxy_wide); goto on_error; } git__free(proxy_wide); if ((error = apply_credentials(s->request, &t->proxy.url, WINHTTP_AUTH_TARGET_PROXY, t->proxy.cred, t->proxy.auth_mechanisms)) < 0) goto on_error; } /* Disable WinHTTP redirects so we can handle them manually. Why, you ask? * http://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/b2ff8879-ab9f-4218-8f09-16d25dff87ae */ if (!WinHttpSetOption(s->request, WINHTTP_OPTION_DISABLE_FEATURE, &disable_redirects, sizeof(disable_redirects))) { git_error_set(GIT_ERROR_OS, "failed to disable redirects"); error = -1; goto on_error; } /* Strip unwanted headers (X-P2P-PeerDist, X-P2P-PeerDistEx) that WinHTTP * adds itself. This option may not be supported by the underlying * platform, so we do not error-check it */ WinHttpSetOption(s->request, WINHTTP_OPTION_PEERDIST_EXTENSION_STATE, &peerdist, sizeof(peerdist)); /* Send Pragma: no-cache header */ if (!WinHttpAddRequestHeaders(s->request, pragma_nocache, (ULONG) -1L, WINHTTP_ADDREQ_FLAG_ADD)) { git_error_set(GIT_ERROR_OS, "failed to add a header to the request"); goto on_error; } if (post_verb == s->verb) { /* Send Content-Type and Accept headers -- only necessary on a POST */ git_buf_clear(&buf); if (git_buf_printf(&buf, "Content-Type: application/x-git-%s-request", s->service) < 0) goto on_error; if (git__utf8_to_16(ct, MAX_CONTENT_TYPE_LEN, git_buf_cstr(&buf)) < 0) { git_error_set(GIT_ERROR_OS, "failed to convert content-type to wide characters"); goto on_error; } if (!WinHttpAddRequestHeaders(s->request, ct, (ULONG)-1L, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE)) { git_error_set(GIT_ERROR_OS, "failed to add a header to the request"); goto on_error; } git_buf_clear(&buf); if (git_buf_printf(&buf, "Accept: application/x-git-%s-result", s->service) < 0) goto on_error; if (git__utf8_to_16(ct, MAX_CONTENT_TYPE_LEN, git_buf_cstr(&buf)) < 0) { git_error_set(GIT_ERROR_OS, "failed to convert accept header to wide characters"); goto on_error; } if (!WinHttpAddRequestHeaders(s->request, ct, (ULONG)-1L, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE)) { git_error_set(GIT_ERROR_OS, "failed to add a header to the request"); goto on_error; } } for (i = 0; i < t->owner->custom_headers.count; i++) { if (t->owner->custom_headers.strings[i]) { git_buf_clear(&buf); git_buf_puts(&buf, t->owner->custom_headers.strings[i]); if (git__utf8_to_16(ct, MAX_CONTENT_TYPE_LEN, git_buf_cstr(&buf)) < 0) { git_error_set(GIT_ERROR_OS, "failed to convert custom header to wide characters"); goto on_error; } if (!WinHttpAddRequestHeaders(s->request, ct, (ULONG)-1L, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE)) { git_error_set(GIT_ERROR_OS, "failed to add a header to the request"); goto on_error; } } } /* If requested, disable certificate validation */ if (strcmp(t->server.url.scheme, "https") == 0) { int flags; if (t->owner->parent.read_flags(&t->owner->parent, &flags) < 0) goto on_error; } if ((error = apply_credentials(s->request, &t->server.url, WINHTTP_AUTH_TARGET_SERVER, t->server.cred, t->server.auth_mechanisms)) < 0) goto on_error; /* We've done everything up to calling WinHttpSendRequest. */ error = 0; on_error: if (error < 0) winhttp_stream_close(s); git__free(proxy_url); git_buf_dispose(&buf); return error; } static int parse_unauthorized_response( int *allowed_types, int *allowed_mechanisms, HINTERNET request) { DWORD supported, first, target; *allowed_types = 0; *allowed_mechanisms = 0; /* WinHttpQueryHeaders() must be called before WinHttpQueryAuthSchemes(). * We can assume this was already done, since we know we are unauthorized. */ if (!WinHttpQueryAuthSchemes(request, &supported, &first, &target)) { git_error_set(GIT_ERROR_OS, "failed to parse supported auth schemes"); return GIT_EAUTH; } if (WINHTTP_AUTH_SCHEME_NTLM & supported) { *allowed_types |= GIT_CREDENTIAL_USERPASS_PLAINTEXT; *allowed_types |= GIT_CREDENTIAL_DEFAULT; *allowed_mechanisms |= GIT_WINHTTP_AUTH_NTLM; } if (WINHTTP_AUTH_SCHEME_NEGOTIATE & supported) { *allowed_types |= GIT_CREDENTIAL_DEFAULT; *allowed_mechanisms |= GIT_WINHTTP_AUTH_NEGOTIATE; } if (WINHTTP_AUTH_SCHEME_BASIC & supported) { *allowed_types |= GIT_CREDENTIAL_USERPASS_PLAINTEXT; *allowed_mechanisms |= GIT_WINHTTP_AUTH_BASIC; } if (WINHTTP_AUTH_SCHEME_DIGEST & supported) { *allowed_types |= GIT_CREDENTIAL_USERPASS_PLAINTEXT; *allowed_mechanisms |= GIT_WINHTTP_AUTH_DIGEST; } return 0; } static int write_chunk(HINTERNET request, const char *buffer, size_t len) { DWORD bytes_written; git_buf buf = GIT_BUF_INIT; /* Chunk header */ git_buf_printf(&buf, "%"PRIXZ"\r\n", len); if (git_buf_oom(&buf)) return -1; if (!WinHttpWriteData(request, git_buf_cstr(&buf), (DWORD)git_buf_len(&buf), &bytes_written)) { git_buf_dispose(&buf); git_error_set(GIT_ERROR_OS, "failed to write chunk header"); return -1; } git_buf_dispose(&buf); /* Chunk body */ if (!WinHttpWriteData(request, buffer, (DWORD)len, &bytes_written)) { git_error_set(GIT_ERROR_OS, "failed to write chunk"); return -1; } /* Chunk footer */ if (!WinHttpWriteData(request, "\r\n", 2, &bytes_written)) { git_error_set(GIT_ERROR_OS, "failed to write chunk footer"); return -1; } return 0; } static int winhttp_close_connection(winhttp_subtransport *t) { int ret = 0; if (t->connection) { if (!WinHttpCloseHandle(t->connection)) { git_error_set(GIT_ERROR_OS, "unable to close connection"); ret = -1; } t->connection = NULL; } if (t->session) { if (!WinHttpCloseHandle(t->session)) { git_error_set(GIT_ERROR_OS, "unable to close session"); ret = -1; } t->session = NULL; } return ret; } static void CALLBACK winhttp_status( HINTERNET connection, DWORD_PTR ctx, DWORD code, LPVOID info, DWORD info_len) { DWORD status; GIT_UNUSED(connection); GIT_UNUSED(info_len); switch (code) { case WINHTTP_CALLBACK_STATUS_SECURE_FAILURE: status = *((DWORD *)info); if ((status & WINHTTP_CALLBACK_STATUS_FLAG_CERT_CN_INVALID)) git_error_set(GIT_ERROR_HTTP, "SSL certificate issued for different common name"); else if ((status & WINHTTP_CALLBACK_STATUS_FLAG_CERT_DATE_INVALID)) git_error_set(GIT_ERROR_HTTP, "SSL certificate has expired"); else if ((status & WINHTTP_CALLBACK_STATUS_FLAG_INVALID_CA)) git_error_set(GIT_ERROR_HTTP, "SSL certificate signed by unknown CA"); else if ((status & WINHTTP_CALLBACK_STATUS_FLAG_INVALID_CERT)) git_error_set(GIT_ERROR_HTTP, "SSL certificate is invalid"); else if ((status & WINHTTP_CALLBACK_STATUS_FLAG_CERT_REV_FAILED)) git_error_set(GIT_ERROR_HTTP, "certificate revocation check failed"); else if ((status & WINHTTP_CALLBACK_STATUS_FLAG_CERT_REVOKED)) git_error_set(GIT_ERROR_HTTP, "SSL certificate was revoked"); else if ((status & WINHTTP_CALLBACK_STATUS_FLAG_SECURITY_CHANNEL_ERROR)) git_error_set(GIT_ERROR_HTTP, "security libraries could not be loaded"); else git_error_set(GIT_ERROR_HTTP, "unknown security error %lu", status); break; case WINHTTP_CALLBACK_STATUS_SENDING_REQUEST: ((winhttp_stream *) ctx)->status_sending_request_reached = 1; break; } } static int winhttp_connect( winhttp_subtransport *t) { wchar_t *wide_host = NULL; int32_t port; wchar_t *wide_ua = NULL; git_buf ipv6 = GIT_BUF_INIT, ua = GIT_BUF_INIT; const char *host; int error = -1; int default_timeout = TIMEOUT_INFINITE; int default_connect_timeout = DEFAULT_CONNECT_TIMEOUT; DWORD protocols = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3; t->session = NULL; t->connection = NULL; /* Prepare port */ if (git__strntol32(&port, t->server.url.port, strlen(t->server.url.port), NULL, 10) < 0) goto on_error; /* IPv6? Add braces around the host. */ if (git_net_url_is_ipv6(&t->server.url)) { if (git_buf_printf(&ipv6, "[%s]", t->server.url.host) < 0) goto on_error; host = ipv6.ptr; } else { host = t->server.url.host; } /* Prepare host */ if (git__utf8_to_16_alloc(&wide_host, host) < 0) { git_error_set(GIT_ERROR_OS, "unable to convert host to wide characters"); goto on_error; } if (git_http__user_agent(&ua) < 0) goto on_error; if (git__utf8_to_16_alloc(&wide_ua, git_buf_cstr(&ua)) < 0) { git_error_set(GIT_ERROR_OS, "unable to convert host to wide characters"); goto on_error; } /* Establish session */ t->session = WinHttpOpen( wide_ua, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (!t->session) { git_error_set(GIT_ERROR_OS, "failed to init WinHTTP"); goto on_error; } /* * Do a best-effort attempt to enable TLS 1.3 and 1.2 but allow this to * fail; if TLS 1.2 or 1.3 support is not available for some reason, * ignore the failure (it will keep the default protocols). */ if (WinHttpSetOption(t->session, WINHTTP_OPTION_SECURE_PROTOCOLS, &protocols, sizeof(protocols)) == FALSE) { protocols &= ~WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3; WinHttpSetOption(t->session, WINHTTP_OPTION_SECURE_PROTOCOLS, &protocols, sizeof(protocols)); } if (!WinHttpSetTimeouts(t->session, default_timeout, default_connect_timeout, default_timeout, default_timeout)) { git_error_set(GIT_ERROR_OS, "failed to set timeouts for WinHTTP"); goto on_error; } /* Establish connection */ t->connection = WinHttpConnect( t->session, wide_host, (INTERNET_PORT) port, 0); if (!t->connection) { git_error_set(GIT_ERROR_OS, "failed to connect to host"); goto on_error; } if (WinHttpSetStatusCallback( t->connection, winhttp_status, WINHTTP_CALLBACK_FLAG_SECURE_FAILURE | WINHTTP_CALLBACK_FLAG_SEND_REQUEST, 0 ) == WINHTTP_INVALID_STATUS_CALLBACK) { git_error_set(GIT_ERROR_OS, "failed to set status callback"); goto on_error; } error = 0; on_error: if (error < 0) winhttp_close_connection(t); git_buf_dispose(&ua); git_buf_dispose(&ipv6); git__free(wide_host); git__free(wide_ua); return error; } static int do_send_request(winhttp_stream *s, size_t len, bool chunked) { int attempts; bool success; if (len > DWORD_MAX) { SetLastError(ERROR_NOT_ENOUGH_MEMORY); return -1; } for (attempts = 0; attempts < 5; attempts++) { if (chunked) { success = WinHttpSendRequest(s->request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH, (DWORD_PTR)s); } else { success = WinHttpSendRequest(s->request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, (DWORD)len, (DWORD_PTR)s); } if (success || GetLastError() != (DWORD)SEC_E_BUFFER_TOO_SMALL) break; } return success ? 0 : -1; } static int send_request(winhttp_stream *s, size_t len, bool chunked) { int request_failed = 1, error, attempts = 0; DWORD ignore_flags, send_request_error; git_error_clear(); while (request_failed && attempts++ < 3) { int cert_valid = 1; int client_cert_requested = 0; request_failed = 0; if ((error = do_send_request(s, len, chunked)) < 0) { send_request_error = GetLastError(); request_failed = 1; switch (send_request_error) { case ERROR_WINHTTP_SECURE_FAILURE: cert_valid = 0; break; case ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED: client_cert_requested = 1; break; default: git_error_set(GIT_ERROR_OS, "failed to send request"); return -1; } } /* * Only check the certificate if we were able to reach the sending request phase, or * received a secure failure error. Otherwise, the server certificate won't be available * since the request wasn't able to complete (e.g. proxy auth required) */ if (!cert_valid || (!request_failed && s->status_sending_request_reached)) { git_error_clear(); if ((error = certificate_check(s, cert_valid)) < 0) { if (!git_error_last()) git_error_set(GIT_ERROR_OS, "user cancelled certificate check"); return error; } } /* if neither the request nor the certificate check returned errors, we're done */ if (!request_failed) return 0; if (!cert_valid) { ignore_flags = no_check_cert_flags; if (!WinHttpSetOption(s->request, WINHTTP_OPTION_SECURITY_FLAGS, &ignore_flags, sizeof(ignore_flags))) { git_error_set(GIT_ERROR_OS, "failed to set security options"); return -1; } } if (client_cert_requested) { /* * Client certificates are not supported, explicitly tell the server that * (it's possible a client certificate was requested but is not required) */ if (!WinHttpSetOption(s->request, WINHTTP_OPTION_CLIENT_CERT_CONTEXT, WINHTTP_NO_CLIENT_CERT_CONTEXT, 0)) { git_error_set(GIT_ERROR_OS, "failed to set client cert context"); return -1; } } } return error; } static int acquire_credentials( HINTERNET request, winhttp_server *server, const char *url_str, git_credential_acquire_cb cred_cb, void *cred_cb_payload) { int allowed_types; int error = 1; if (parse_unauthorized_response(&allowed_types, &server->auth_mechanisms, request) < 0) return -1; if (allowed_types) { git_credential_free(server->cred); server->cred = NULL; /* Start with URL-specified credentials, if there were any. */ if (!server->url_cred_presented && server->url.username && server->url.password) { error = acquire_url_cred(&server->cred, allowed_types, server->url.username, server->url.password); server->url_cred_presented = 1; if (error < 0) return error; } /* Next use the user-defined callback, if there is one. */ if (error > 0 && cred_cb) { error = cred_cb(&server->cred, url_str, server->url.username, allowed_types, cred_cb_payload); /* Treat GIT_PASSTHROUGH as though git_credential_acquire_cb isn't set */ if (error == GIT_PASSTHROUGH) error = 1; else if (error < 0) return error; } /* Finally, invoke the fallback default credential lookup. */ if (error > 0) { error = acquire_fallback_cred(&server->cred, url_str, allowed_types); if (error < 0) return error; } } /* * No error occurred but we could not find appropriate credentials. * This behaves like a pass-through. */ return error; } static int winhttp_stream_read( git_smart_subtransport_stream *stream, char *buffer, size_t buf_size, size_t *bytes_read) { winhttp_stream *s = (winhttp_stream *)stream; winhttp_subtransport *t = OWNING_SUBTRANSPORT(s); DWORD dw_bytes_read; char replay_count = 0; int error; replay: /* Enforce a reasonable cap on the number of replays */ if (replay_count++ >= GIT_HTTP_REPLAY_MAX) { git_error_set(GIT_ERROR_HTTP, "too many redirects or authentication replays"); return GIT_ERROR; /* not GIT_EAUTH because the exact cause is not clear */ } /* Connect if necessary */ if (!s->request && winhttp_stream_connect(s) < 0) return -1; if (!s->received_response) { DWORD status_code, status_code_length, content_type_length, bytes_written; char expected_content_type_8[MAX_CONTENT_TYPE_LEN]; wchar_t expected_content_type[MAX_CONTENT_TYPE_LEN], content_type[MAX_CONTENT_TYPE_LEN]; if (!s->sent_request) { if ((error = send_request(s, s->post_body_len, false)) < 0) return error; s->sent_request = 1; } if (s->chunked) { GIT_ASSERT(s->verb == post_verb); /* Flush, if necessary */ if (s->chunk_buffer_len > 0 && write_chunk(s->request, s->chunk_buffer, s->chunk_buffer_len) < 0) return -1; s->chunk_buffer_len = 0; /* Write the final chunk. */ if (!WinHttpWriteData(s->request, "0\r\n\r\n", 5, &bytes_written)) { git_error_set(GIT_ERROR_OS, "failed to write final chunk"); return -1; } } else if (s->post_body) { char *buffer; DWORD len = s->post_body_len, bytes_read; if (INVALID_SET_FILE_POINTER == SetFilePointer(s->post_body, 0, 0, FILE_BEGIN) && NO_ERROR != GetLastError()) { git_error_set(GIT_ERROR_OS, "failed to reset file pointer"); return -1; } buffer = git__malloc(CACHED_POST_BODY_BUF_SIZE); GIT_ERROR_CHECK_ALLOC(buffer); while (len > 0) { DWORD bytes_written; if (!ReadFile(s->post_body, buffer, min(CACHED_POST_BODY_BUF_SIZE, len), &bytes_read, NULL) || !bytes_read) { git__free(buffer); git_error_set(GIT_ERROR_OS, "failed to read from temp file"); return -1; } if (!WinHttpWriteData(s->request, buffer, bytes_read, &bytes_written)) { git__free(buffer); git_error_set(GIT_ERROR_OS, "failed to write data"); return -1; } len -= bytes_read; GIT_ASSERT(bytes_read == bytes_written); } git__free(buffer); /* Eagerly close the temp file */ CloseHandle(s->post_body); s->post_body = NULL; } if (!WinHttpReceiveResponse(s->request, 0)) { git_error_set(GIT_ERROR_OS, "failed to receive response"); return -1; } /* Verify that we got a 200 back */ status_code_length = sizeof(status_code); if (!WinHttpQueryHeaders(s->request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &status_code, &status_code_length, WINHTTP_NO_HEADER_INDEX)) { git_error_set(GIT_ERROR_OS, "failed to retrieve status code"); return -1; } /* The implementation of WinHTTP prior to Windows 7 will not * redirect to an identical URI. Some Git hosters use self-redirects * as part of their DoS mitigation strategy. Check first to see if we * have a redirect status code, and that we haven't already streamed * a post body. (We can't replay a streamed POST.) */ if (!s->chunked && (HTTP_STATUS_MOVED == status_code || HTTP_STATUS_REDIRECT == status_code || (HTTP_STATUS_REDIRECT_METHOD == status_code && get_verb == s->verb) || HTTP_STATUS_REDIRECT_KEEP_VERB == status_code || HTTP_STATUS_PERMANENT_REDIRECT == status_code)) { /* Check for Windows 7. This workaround is only necessary on * Windows Vista and earlier. Windows 7 is version 6.1. */ wchar_t *location; DWORD location_length; char *location8; /* OK, fetch the Location header from the redirect. */ if (WinHttpQueryHeaders(s->request, WINHTTP_QUERY_LOCATION, WINHTTP_HEADER_NAME_BY_INDEX, WINHTTP_NO_OUTPUT_BUFFER, &location_length, WINHTTP_NO_HEADER_INDEX) || GetLastError() != ERROR_INSUFFICIENT_BUFFER) { git_error_set(GIT_ERROR_OS, "failed to read Location header"); return -1; } location = git__malloc(location_length); GIT_ERROR_CHECK_ALLOC(location); if (!WinHttpQueryHeaders(s->request, WINHTTP_QUERY_LOCATION, WINHTTP_HEADER_NAME_BY_INDEX, location, &location_length, WINHTTP_NO_HEADER_INDEX)) { git_error_set(GIT_ERROR_OS, "failed to read Location header"); git__free(location); return -1; } /* Convert the Location header to UTF-8 */ if (git__utf16_to_8_alloc(&location8, location) < 0) { git_error_set(GIT_ERROR_OS, "failed to convert Location header to UTF-8"); git__free(location); return -1; } git__free(location); /* Replay the request */ winhttp_stream_close(s); if (!git__prefixcmp_icase(location8, prefix_https)) { /* Upgrade to secure connection; disconnect and start over */ if (git_net_url_apply_redirect(&t->server.url, location8, s->service_url) < 0) { git__free(location8); return -1; } winhttp_close_connection(t); if (winhttp_connect(t) < 0) return -1; } git__free(location8); goto replay; } /* Handle authentication failures */ if (status_code == HTTP_STATUS_DENIED) { int error = acquire_credentials(s->request, &t->server, t->owner->url, t->owner->cred_acquire_cb, t->owner->cred_acquire_payload); if (error < 0) { return error; } else if (!error) { GIT_ASSERT(t->server.cred); winhttp_stream_close(s); goto replay; } } else if (status_code == HTTP_STATUS_PROXY_AUTH_REQ) { int error = acquire_credentials(s->request, &t->proxy, t->owner->proxy.url, t->owner->proxy.credentials, t->owner->proxy.payload); if (error < 0) { return error; } else if (!error) { GIT_ASSERT(t->proxy.cred); winhttp_stream_close(s); goto replay; } } if (HTTP_STATUS_OK != status_code) { git_error_set(GIT_ERROR_HTTP, "request failed with status code: %lu", status_code); return -1; } /* Verify that we got the correct content-type back */ if (post_verb == s->verb) p_snprintf(expected_content_type_8, MAX_CONTENT_TYPE_LEN, "application/x-git-%s-result", s->service); else p_snprintf(expected_content_type_8, MAX_CONTENT_TYPE_LEN, "application/x-git-%s-advertisement", s->service); if (git__utf8_to_16(expected_content_type, MAX_CONTENT_TYPE_LEN, expected_content_type_8) < 0) { git_error_set(GIT_ERROR_OS, "failed to convert expected content-type to wide characters"); return -1; } content_type_length = sizeof(content_type); if (!WinHttpQueryHeaders(s->request, WINHTTP_QUERY_CONTENT_TYPE, WINHTTP_HEADER_NAME_BY_INDEX, &content_type, &content_type_length, WINHTTP_NO_HEADER_INDEX)) { git_error_set(GIT_ERROR_OS, "failed to retrieve response content-type"); return -1; } if (wcscmp(expected_content_type, content_type)) { git_error_set(GIT_ERROR_HTTP, "received unexpected content-type"); return -1; } s->received_response = 1; } if (!WinHttpReadData(s->request, (LPVOID)buffer, (DWORD)buf_size, &dw_bytes_read)) { git_error_set(GIT_ERROR_OS, "failed to read data"); return -1; } *bytes_read = dw_bytes_read; return 0; } static int winhttp_stream_write_single( git_smart_subtransport_stream *stream, const char *buffer, size_t len) { winhttp_stream *s = (winhttp_stream *)stream; DWORD bytes_written; int error; if (!s->request && winhttp_stream_connect(s) < 0) return -1; /* This implementation of write permits only a single call. */ if (s->sent_request) { git_error_set(GIT_ERROR_HTTP, "subtransport configured for only one write"); return -1; } if ((error = send_request(s, len, false)) < 0) return error; s->sent_request = 1; if (!WinHttpWriteData(s->request, (LPCVOID)buffer, (DWORD)len, &bytes_written)) { git_error_set(GIT_ERROR_OS, "failed to write data"); return -1; } GIT_ASSERT((DWORD)len == bytes_written); return 0; } static int put_uuid_string(LPWSTR buffer, size_t buffer_len_cch) { UUID uuid; RPC_STATUS status = UuidCreate(&uuid); int result; if (RPC_S_OK != status && RPC_S_UUID_LOCAL_ONLY != status && RPC_S_UUID_NO_ADDRESS != status) { git_error_set(GIT_ERROR_HTTP, "unable to generate name for temp file"); return -1; } if (buffer_len_cch < UUID_LENGTH_CCH + 1) { git_error_set(GIT_ERROR_HTTP, "buffer too small for name of temp file"); return -1; } #if !defined(__MINGW32__) || defined(MINGW_HAS_SECURE_API) result = swprintf_s(buffer, buffer_len_cch, #else result = wsprintfW(buffer, #endif L"%08x%04x%04x%02x%02x%02x%02x%02x%02x%02x%02x", uuid.Data1, uuid.Data2, uuid.Data3, uuid.Data4[0], uuid.Data4[1], uuid.Data4[2], uuid.Data4[3], uuid.Data4[4], uuid.Data4[5], uuid.Data4[6], uuid.Data4[7]); if (result < UUID_LENGTH_CCH) { git_error_set(GIT_ERROR_OS, "unable to generate name for temp file"); return -1; } return 0; } static int get_temp_file(LPWSTR buffer, DWORD buffer_len_cch) { size_t len; if (!GetTempPathW(buffer_len_cch, buffer)) { git_error_set(GIT_ERROR_OS, "failed to get temp path"); return -1; } len = wcslen(buffer); if (buffer[len - 1] != '\\' && len < buffer_len_cch) buffer[len++] = '\\'; if (put_uuid_string(&buffer[len], (size_t)buffer_len_cch - len) < 0) return -1; return 0; } static int winhttp_stream_write_buffered( git_smart_subtransport_stream *stream, const char *buffer, size_t len) { winhttp_stream *s = (winhttp_stream *)stream; DWORD bytes_written; if (!s->request && winhttp_stream_connect(s) < 0) return -1; /* Buffer the payload, using a temporary file so we delegate * memory management of the data to the operating system. */ if (!s->post_body) { wchar_t temp_path[MAX_PATH + 1]; if (get_temp_file(temp_path, MAX_PATH + 1) < 0) return -1; s->post_body = CreateFileW(temp_path, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_DELETE, NULL, CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE | FILE_FLAG_SEQUENTIAL_SCAN, NULL); if (INVALID_HANDLE_VALUE == s->post_body) { s->post_body = NULL; git_error_set(GIT_ERROR_OS, "failed to create temporary file"); return -1; } } if (!WriteFile(s->post_body, buffer, (DWORD)len, &bytes_written, NULL)) { git_error_set(GIT_ERROR_OS, "failed to write to temporary file"); return -1; } GIT_ASSERT((DWORD)len == bytes_written); s->post_body_len += bytes_written; return 0; } static int winhttp_stream_write_chunked( git_smart_subtransport_stream *stream, const char *buffer, size_t len) { winhttp_stream *s = (winhttp_stream *)stream; int error; if (!s->request && winhttp_stream_connect(s) < 0) return -1; if (!s->sent_request) { /* Send Transfer-Encoding: chunked header */ if (!WinHttpAddRequestHeaders(s->request, transfer_encoding, (ULONG) -1L, WINHTTP_ADDREQ_FLAG_ADD)) { git_error_set(GIT_ERROR_OS, "failed to add a header to the request"); return -1; } if ((error = send_request(s, 0, true)) < 0) return error; s->sent_request = 1; } if (len > CACHED_POST_BODY_BUF_SIZE) { /* Flush, if necessary */ if (s->chunk_buffer_len > 0) { if (write_chunk(s->request, s->chunk_buffer, s->chunk_buffer_len) < 0) return -1; s->chunk_buffer_len = 0; } /* Write chunk directly */ if (write_chunk(s->request, buffer, len) < 0) return -1; } else { /* Append as much to the buffer as we can */ int count = (int)min(CACHED_POST_BODY_BUF_SIZE - s->chunk_buffer_len, len); if (!s->chunk_buffer) { s->chunk_buffer = git__malloc(CACHED_POST_BODY_BUF_SIZE); GIT_ERROR_CHECK_ALLOC(s->chunk_buffer); } memcpy(s->chunk_buffer + s->chunk_buffer_len, buffer, count); s->chunk_buffer_len += count; buffer += count; len -= count; /* Is the buffer full? If so, then flush */ if (CACHED_POST_BODY_BUF_SIZE == s->chunk_buffer_len) { if (write_chunk(s->request, s->chunk_buffer, s->chunk_buffer_len) < 0) return -1; s->chunk_buffer_len = 0; /* Is there any remaining data from the source? */ if (len > 0) { memcpy(s->chunk_buffer, buffer, len); s->chunk_buffer_len = (unsigned int)len; } } } return 0; } static void winhttp_stream_free(git_smart_subtransport_stream *stream) { winhttp_stream *s = (winhttp_stream *)stream; winhttp_stream_close(s); git__free(s); } static int winhttp_stream_alloc(winhttp_subtransport *t, winhttp_stream **stream) { winhttp_stream *s; if (!stream) return -1; s = git__calloc(1, sizeof(winhttp_stream)); GIT_ERROR_CHECK_ALLOC(s); s->parent.subtransport = &t->parent; s->parent.read = winhttp_stream_read; s->parent.write = winhttp_stream_write_single; s->parent.free = winhttp_stream_free; *stream = s; return 0; } static int winhttp_uploadpack_ls( winhttp_subtransport *t, winhttp_stream *s) { GIT_UNUSED(t); s->service = upload_pack_service; s->service_url = upload_pack_ls_service_url; s->verb = get_verb; return 0; } static int winhttp_uploadpack( winhttp_subtransport *t, winhttp_stream *s) { GIT_UNUSED(t); s->service = upload_pack_service; s->service_url = upload_pack_service_url; s->verb = post_verb; return 0; } static int winhttp_receivepack_ls( winhttp_subtransport *t, winhttp_stream *s) { GIT_UNUSED(t); s->service = receive_pack_service; s->service_url = receive_pack_ls_service_url; s->verb = get_verb; return 0; } static int winhttp_receivepack( winhttp_subtransport *t, winhttp_stream *s) { GIT_UNUSED(t); /* WinHTTP only supports Transfer-Encoding: chunked * on Windows Vista (NT 6.0) and higher. */ s->chunked = git_has_win32_version(6, 0, 0); if (s->chunked) s->parent.write = winhttp_stream_write_chunked; else s->parent.write = winhttp_stream_write_buffered; s->service = receive_pack_service; s->service_url = receive_pack_service_url; s->verb = post_verb; return 0; } static int winhttp_action( git_smart_subtransport_stream **stream, git_smart_subtransport *subtransport, const char *url, git_smart_service_t action) { winhttp_subtransport *t = (winhttp_subtransport *)subtransport; winhttp_stream *s; int ret = -1; if (!t->connection) if ((ret = git_net_url_parse(&t->server.url, url)) < 0 || (ret = winhttp_connect(t)) < 0) return ret; if (winhttp_stream_alloc(t, &s) < 0) return -1; if (!stream) return -1; switch (action) { case GIT_SERVICE_UPLOADPACK_LS: ret = winhttp_uploadpack_ls(t, s); break; case GIT_SERVICE_UPLOADPACK: ret = winhttp_uploadpack(t, s); break; case GIT_SERVICE_RECEIVEPACK_LS: ret = winhttp_receivepack_ls(t, s); break; case GIT_SERVICE_RECEIVEPACK: ret = winhttp_receivepack(t, s); break; default: GIT_ASSERT(0); } if (!ret) *stream = &s->parent; return ret; } static int winhttp_close(git_smart_subtransport *subtransport) { winhttp_subtransport *t = (winhttp_subtransport *)subtransport; git_net_url_dispose(&t->server.url); git_net_url_dispose(&t->proxy.url); if (t->server.cred) { t->server.cred->free(t->server.cred); t->server.cred = NULL; } if (t->proxy.cred) { t->proxy.cred->free(t->proxy.cred); t->proxy.cred = NULL; } return winhttp_close_connection(t); } static void winhttp_free(git_smart_subtransport *subtransport) { winhttp_subtransport *t = (winhttp_subtransport *)subtransport; winhttp_close(subtransport); git__free(t); } int git_smart_subtransport_http(git_smart_subtransport **out, git_transport *owner, void *param) { winhttp_subtransport *t; GIT_UNUSED(param); if (!out) return -1; t = git__calloc(1, sizeof(winhttp_subtransport)); GIT_ERROR_CHECK_ALLOC(t); t->owner = (transport_smart *)owner; t->parent.action = winhttp_action; t->parent.close = winhttp_close; t->parent.free = winhttp_free; *out = (git_smart_subtransport *) t; return 0; } #endif /* GIT_WINHTTP */
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/transports/auth_ntlm.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "git2.h" #include "common.h" #include "buffer.h" #include "auth.h" #include "auth_ntlm.h" #include "git2/sys/credential.h" #ifdef GIT_NTLM #include "ntlmclient.h" typedef struct { git_http_auth_context parent; ntlm_client *ntlm; char *challenge; bool complete; } http_auth_ntlm_context; static int ntlm_set_challenge( git_http_auth_context *c, const char *challenge) { http_auth_ntlm_context *ctx = (http_auth_ntlm_context *)c; GIT_ASSERT_ARG(ctx); GIT_ASSERT_ARG(challenge); git__free(ctx->challenge); ctx->challenge = git__strdup(challenge); GIT_ERROR_CHECK_ALLOC(ctx->challenge); return 0; } static int ntlm_set_credentials(http_auth_ntlm_context *ctx, git_credential *_cred) { git_credential_userpass_plaintext *cred; const char *sep, *username; char *domain = NULL, *domainuser = NULL; int error = 0; GIT_ASSERT(_cred->credtype == GIT_CREDENTIAL_USERPASS_PLAINTEXT); cred = (git_credential_userpass_plaintext *)_cred; if ((sep = strchr(cred->username, '\\')) != NULL) { domain = git__strndup(cred->username, (sep - cred->username)); GIT_ERROR_CHECK_ALLOC(domain); domainuser = git__strdup(sep + 1); GIT_ERROR_CHECK_ALLOC(domainuser); username = domainuser; } else { username = cred->username; } if (ntlm_client_set_credentials(ctx->ntlm, username, domain, cred->password) < 0) { git_error_set(GIT_ERROR_NET, "could not set credentials: %s", ntlm_client_errmsg(ctx->ntlm)); error = -1; goto done; } done: git__free(domain); git__free(domainuser); return error; } static int ntlm_next_token( git_buf *buf, git_http_auth_context *c, git_credential *cred) { http_auth_ntlm_context *ctx = (http_auth_ntlm_context *)c; git_buf input_buf = GIT_BUF_INIT; const unsigned char *msg; size_t challenge_len, msg_len; int error = GIT_EAUTH; GIT_ASSERT_ARG(buf); GIT_ASSERT_ARG(ctx); GIT_ASSERT(ctx->ntlm); challenge_len = ctx->challenge ? strlen(ctx->challenge) : 0; if (ctx->complete) ntlm_client_reset(ctx->ntlm); /* * Set us complete now since it's the default case; the one * incomplete case (successfully created a client request) * will explicitly set that it requires a second step. */ ctx->complete = true; if (cred && ntlm_set_credentials(ctx, cred) != 0) goto done; if (challenge_len < 4) { git_error_set(GIT_ERROR_NET, "no ntlm challenge sent from server"); goto done; } else if (challenge_len == 4) { if (memcmp(ctx->challenge, "NTLM", 4) != 0) { git_error_set(GIT_ERROR_NET, "server did not request NTLM"); goto done; } if (ntlm_client_negotiate(&msg, &msg_len, ctx->ntlm) != 0) { git_error_set(GIT_ERROR_NET, "ntlm authentication failed: %s", ntlm_client_errmsg(ctx->ntlm)); goto done; } ctx->complete = false; } else { if (memcmp(ctx->challenge, "NTLM ", 5) != 0) { git_error_set(GIT_ERROR_NET, "challenge from server was not NTLM"); goto done; } if (git_buf_decode_base64(&input_buf, ctx->challenge + 5, challenge_len - 5) < 0) { git_error_set(GIT_ERROR_NET, "invalid NTLM challenge from server"); goto done; } if (ntlm_client_set_challenge(ctx->ntlm, (const unsigned char *)input_buf.ptr, input_buf.size) != 0) { git_error_set(GIT_ERROR_NET, "ntlm challenge failed: %s", ntlm_client_errmsg(ctx->ntlm)); goto done; } if (ntlm_client_response(&msg, &msg_len, ctx->ntlm) != 0) { git_error_set(GIT_ERROR_NET, "ntlm authentication failed: %s", ntlm_client_errmsg(ctx->ntlm)); goto done; } } git_buf_puts(buf, "NTLM "); git_buf_encode_base64(buf, (const char *)msg, msg_len); if (git_buf_oom(buf)) goto done; error = 0; done: git_buf_dispose(&input_buf); return error; } static int ntlm_is_complete(git_http_auth_context *c) { http_auth_ntlm_context *ctx = (http_auth_ntlm_context *)c; GIT_ASSERT_ARG(ctx); return (ctx->complete == true); } static void ntlm_context_free(git_http_auth_context *c) { http_auth_ntlm_context *ctx = (http_auth_ntlm_context *)c; ntlm_client_free(ctx->ntlm); git__free(ctx->challenge); git__free(ctx); } static int ntlm_init_context( http_auth_ntlm_context *ctx, const git_net_url *url) { GIT_UNUSED(url); if ((ctx->ntlm = ntlm_client_init(NTLM_CLIENT_DEFAULTS)) == NULL) { git_error_set_oom(); return -1; } return 0; } int git_http_auth_ntlm( git_http_auth_context **out, const git_net_url *url) { http_auth_ntlm_context *ctx; GIT_UNUSED(url); *out = NULL; ctx = git__calloc(1, sizeof(http_auth_ntlm_context)); GIT_ERROR_CHECK_ALLOC(ctx); if (ntlm_init_context(ctx, url) < 0) { git__free(ctx); return -1; } ctx->parent.type = GIT_HTTP_AUTH_NTLM; ctx->parent.credtypes = GIT_CREDENTIAL_USERPASS_PLAINTEXT; ctx->parent.connection_affinity = 1; ctx->parent.set_challenge = ntlm_set_challenge; ctx->parent.next_token = ntlm_next_token; ctx->parent.is_complete = ntlm_is_complete; ctx->parent.free = ntlm_context_free; *out = (git_http_auth_context *)ctx; return 0; } #endif /* GIT_NTLM */
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/transports/smart_protocol.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "common.h" #include "git2.h" #include "git2/odb_backend.h" #include "smart.h" #include "refs.h" #include "repository.h" #include "push.h" #include "pack-objects.h" #include "remote.h" #include "util.h" #include "revwalk.h" #define NETWORK_XFER_THRESHOLD (100*1024) /* The minimal interval between progress updates (in seconds). */ #define MIN_PROGRESS_UPDATE_INTERVAL 0.5 bool git_smart__ofs_delta_enabled = true; int git_smart__store_refs(transport_smart *t, int flushes) { gitno_buffer *buf = &t->buffer; git_vector *refs = &t->refs; int error, flush = 0, recvd; const char *line_end = NULL; git_pkt *pkt = NULL; size_t i; /* Clear existing refs in case git_remote_connect() is called again * after git_remote_disconnect(). */ git_vector_foreach(refs, i, pkt) { git_pkt_free(pkt); } git_vector_clear(refs); pkt = NULL; do { if (buf->offset > 0) error = git_pkt_parse_line(&pkt, &line_end, buf->data, buf->offset); else error = GIT_EBUFS; if (error < 0 && error != GIT_EBUFS) return error; if (error == GIT_EBUFS) { if ((recvd = gitno_recv(buf)) < 0) return recvd; if (recvd == 0) { git_error_set(GIT_ERROR_NET, "early EOF"); return GIT_EEOF; } continue; } if (gitno_consume(buf, line_end) < 0) return -1; if (pkt->type == GIT_PKT_ERR) { git_error_set(GIT_ERROR_NET, "remote error: %s", ((git_pkt_err *)pkt)->error); git__free(pkt); return -1; } if (pkt->type != GIT_PKT_FLUSH && git_vector_insert(refs, pkt) < 0) return -1; if (pkt->type == GIT_PKT_FLUSH) { flush++; git_pkt_free(pkt); } } while (flush < flushes); return flush; } static int append_symref(const char **out, git_vector *symrefs, const char *ptr) { int error; const char *end; git_buf buf = GIT_BUF_INIT; git_refspec *mapping = NULL; ptr += strlen(GIT_CAP_SYMREF); if (*ptr != '=') goto on_invalid; ptr++; if (!(end = strchr(ptr, ' ')) && !(end = strchr(ptr, '\0'))) goto on_invalid; if ((error = git_buf_put(&buf, ptr, end - ptr)) < 0) return error; /* symref mapping has refspec format */ mapping = git__calloc(1, sizeof(git_refspec)); GIT_ERROR_CHECK_ALLOC(mapping); error = git_refspec__parse(mapping, git_buf_cstr(&buf), true); git_buf_dispose(&buf); /* if the error isn't OOM, then it's a parse error; let's use a nicer message */ if (error < 0) { if (git_error_last()->klass != GIT_ERROR_NOMEMORY) goto on_invalid; git__free(mapping); return error; } if ((error = git_vector_insert(symrefs, mapping)) < 0) return error; *out = end; return 0; on_invalid: git_error_set(GIT_ERROR_NET, "remote sent invalid symref"); git_refspec__dispose(mapping); git__free(mapping); return -1; } int git_smart__detect_caps(git_pkt_ref *pkt, transport_smart_caps *caps, git_vector *symrefs) { const char *ptr; /* No refs or capabilites, odd but not a problem */ if (pkt == NULL || pkt->capabilities == NULL) return GIT_ENOTFOUND; ptr = pkt->capabilities; while (ptr != NULL && *ptr != '\0') { if (*ptr == ' ') ptr++; if (git_smart__ofs_delta_enabled && !git__prefixcmp(ptr, GIT_CAP_OFS_DELTA)) { caps->common = caps->ofs_delta = 1; ptr += strlen(GIT_CAP_OFS_DELTA); continue; } /* Keep multi_ack_detailed before multi_ack */ if (!git__prefixcmp(ptr, GIT_CAP_MULTI_ACK_DETAILED)) { caps->common = caps->multi_ack_detailed = 1; ptr += strlen(GIT_CAP_MULTI_ACK_DETAILED); continue; } if (!git__prefixcmp(ptr, GIT_CAP_MULTI_ACK)) { caps->common = caps->multi_ack = 1; ptr += strlen(GIT_CAP_MULTI_ACK); continue; } if (!git__prefixcmp(ptr, GIT_CAP_INCLUDE_TAG)) { caps->common = caps->include_tag = 1; ptr += strlen(GIT_CAP_INCLUDE_TAG); continue; } /* Keep side-band check after side-band-64k */ if (!git__prefixcmp(ptr, GIT_CAP_SIDE_BAND_64K)) { caps->common = caps->side_band_64k = 1; ptr += strlen(GIT_CAP_SIDE_BAND_64K); continue; } if (!git__prefixcmp(ptr, GIT_CAP_SIDE_BAND)) { caps->common = caps->side_band = 1; ptr += strlen(GIT_CAP_SIDE_BAND); continue; } if (!git__prefixcmp(ptr, GIT_CAP_DELETE_REFS)) { caps->common = caps->delete_refs = 1; ptr += strlen(GIT_CAP_DELETE_REFS); continue; } if (!git__prefixcmp(ptr, GIT_CAP_THIN_PACK)) { caps->common = caps->thin_pack = 1; ptr += strlen(GIT_CAP_THIN_PACK); continue; } if (!git__prefixcmp(ptr, GIT_CAP_SYMREF)) { int error; if ((error = append_symref(&ptr, symrefs, ptr)) < 0) return error; continue; } /* We don't know this capability, so skip it */ ptr = strchr(ptr, ' '); } return 0; } static int recv_pkt(git_pkt **out_pkt, git_pkt_type *out_type, gitno_buffer *buf) { const char *ptr = buf->data, *line_end = ptr; git_pkt *pkt = NULL; int error = 0, ret; do { if (buf->offset > 0) error = git_pkt_parse_line(&pkt, &line_end, ptr, buf->offset); else error = GIT_EBUFS; if (error == 0) break; /* return the pkt */ if (error < 0 && error != GIT_EBUFS) return error; if ((ret = gitno_recv(buf)) < 0) { return ret; } else if (ret == 0) { git_error_set(GIT_ERROR_NET, "early EOF"); return GIT_EEOF; } } while (error); if (gitno_consume(buf, line_end) < 0) return -1; if (out_type != NULL) *out_type = pkt->type; if (out_pkt != NULL) *out_pkt = pkt; else git__free(pkt); return error; } static int store_common(transport_smart *t) { git_pkt *pkt = NULL; gitno_buffer *buf = &t->buffer; int error; do { if ((error = recv_pkt(&pkt, NULL, buf)) < 0) return error; if (pkt->type != GIT_PKT_ACK) { git__free(pkt); return 0; } if (git_vector_insert(&t->common, pkt) < 0) { git__free(pkt); return -1; } } while (1); return 0; } static int wait_while_ack(gitno_buffer *buf) { int error; git_pkt *pkt = NULL; git_pkt_ack *ack = NULL; while (1) { git_pkt_free(pkt); if ((error = recv_pkt(&pkt, NULL, buf)) < 0) return error; if (pkt->type == GIT_PKT_NAK) break; if (pkt->type != GIT_PKT_ACK) continue; ack = (git_pkt_ack*)pkt; if (ack->status != GIT_ACK_CONTINUE && ack->status != GIT_ACK_COMMON && ack->status != GIT_ACK_READY) { break; } } git_pkt_free(pkt); return 0; } int git_smart__negotiate_fetch(git_transport *transport, git_repository *repo, const git_remote_head * const *wants, size_t count) { transport_smart *t = (transport_smart *)transport; git_revwalk__push_options opts = GIT_REVWALK__PUSH_OPTIONS_INIT; gitno_buffer *buf = &t->buffer; git_buf data = GIT_BUF_INIT; git_revwalk *walk = NULL; int error = -1; git_pkt_type pkt_type; unsigned int i; git_oid oid; if ((error = git_pkt_buffer_wants(wants, count, &t->caps, &data)) < 0) return error; if ((error = git_revwalk_new(&walk, repo)) < 0) goto on_error; opts.insert_by_date = 1; if ((error = git_revwalk__push_glob(walk, "refs/*", &opts)) < 0) goto on_error; /* * Our support for ACK extensions is simply to parse them. On * the first ACK we will accept that as enough common * objects. We give up if we haven't found an answer in the * first 256 we send. */ i = 0; while (i < 256) { error = git_revwalk_next(&oid, walk); if (error < 0) { if (GIT_ITEROVER == error) break; goto on_error; } git_pkt_buffer_have(&oid, &data); i++; if (i % 20 == 0) { if (t->cancelled.val) { git_error_set(GIT_ERROR_NET, "The fetch was cancelled by the user"); error = GIT_EUSER; goto on_error; } git_pkt_buffer_flush(&data); if (git_buf_oom(&data)) { error = -1; goto on_error; } if ((error = git_smart__negotiation_step(&t->parent, data.ptr, data.size)) < 0) goto on_error; git_buf_clear(&data); if (t->caps.multi_ack || t->caps.multi_ack_detailed) { if ((error = store_common(t)) < 0) goto on_error; } else { if ((error = recv_pkt(NULL, &pkt_type, buf)) < 0) goto on_error; if (pkt_type == GIT_PKT_ACK) { break; } else if (pkt_type == GIT_PKT_NAK) { continue; } else { git_error_set(GIT_ERROR_NET, "unexpected pkt type"); error = -1; goto on_error; } } } if (t->common.length > 0) break; if (i % 20 == 0 && t->rpc) { git_pkt_ack *pkt; unsigned int j; if ((error = git_pkt_buffer_wants(wants, count, &t->caps, &data)) < 0) goto on_error; git_vector_foreach(&t->common, j, pkt) { if ((error = git_pkt_buffer_have(&pkt->oid, &data)) < 0) goto on_error; } if (git_buf_oom(&data)) { error = -1; goto on_error; } } } /* Tell the other end that we're done negotiating */ if (t->rpc && t->common.length > 0) { git_pkt_ack *pkt; unsigned int j; if ((error = git_pkt_buffer_wants(wants, count, &t->caps, &data)) < 0) goto on_error; git_vector_foreach(&t->common, j, pkt) { if ((error = git_pkt_buffer_have(&pkt->oid, &data)) < 0) goto on_error; } if (git_buf_oom(&data)) { error = -1; goto on_error; } } if ((error = git_pkt_buffer_done(&data)) < 0) goto on_error; if (t->cancelled.val) { git_error_set(GIT_ERROR_NET, "The fetch was cancelled by the user"); error = GIT_EUSER; goto on_error; } if ((error = git_smart__negotiation_step(&t->parent, data.ptr, data.size)) < 0) goto on_error; git_buf_dispose(&data); git_revwalk_free(walk); /* Now let's eat up whatever the server gives us */ if (!t->caps.multi_ack && !t->caps.multi_ack_detailed) { if ((error = recv_pkt(NULL, &pkt_type, buf)) < 0) return error; if (pkt_type != GIT_PKT_ACK && pkt_type != GIT_PKT_NAK) { git_error_set(GIT_ERROR_NET, "unexpected pkt type"); return -1; } } else { error = wait_while_ack(buf); } return error; on_error: git_revwalk_free(walk); git_buf_dispose(&data); return error; } static int no_sideband(transport_smart *t, struct git_odb_writepack *writepack, gitno_buffer *buf, git_indexer_progress *stats) { int recvd; do { if (t->cancelled.val) { git_error_set(GIT_ERROR_NET, "the fetch was cancelled by the user"); return GIT_EUSER; } if (writepack->append(writepack, buf->data, buf->offset, stats) < 0) return -1; gitno_consume_n(buf, buf->offset); if ((recvd = gitno_recv(buf)) < 0) return recvd; } while(recvd > 0); if (writepack->commit(writepack, stats) < 0) return -1; return 0; } struct network_packetsize_payload { git_indexer_progress_cb callback; void *payload; git_indexer_progress *stats; size_t last_fired_bytes; }; static int network_packetsize(size_t received, void *payload) { struct network_packetsize_payload *npp = (struct network_packetsize_payload*)payload; /* Accumulate bytes */ npp->stats->received_bytes += received; /* Fire notification if the threshold is reached */ if ((npp->stats->received_bytes - npp->last_fired_bytes) > NETWORK_XFER_THRESHOLD) { npp->last_fired_bytes = npp->stats->received_bytes; if (npp->callback(npp->stats, npp->payload)) return GIT_EUSER; } return 0; } int git_smart__download_pack( git_transport *transport, git_repository *repo, git_indexer_progress *stats, git_indexer_progress_cb progress_cb, void *progress_payload) { transport_smart *t = (transport_smart *)transport; gitno_buffer *buf = &t->buffer; git_odb *odb; struct git_odb_writepack *writepack = NULL; int error = 0; struct network_packetsize_payload npp = {0}; memset(stats, 0, sizeof(git_indexer_progress)); if (progress_cb) { npp.callback = progress_cb; npp.payload = progress_payload; npp.stats = stats; t->packetsize_cb = &network_packetsize; t->packetsize_payload = &npp; /* We might have something in the buffer already from negotiate_fetch */ if (t->buffer.offset > 0 && !t->cancelled.val) if (t->packetsize_cb(t->buffer.offset, t->packetsize_payload)) git_atomic32_set(&t->cancelled, 1); } if ((error = git_repository_odb__weakptr(&odb, repo)) < 0 || ((error = git_odb_write_pack(&writepack, odb, progress_cb, progress_payload)) != 0)) goto done; /* * If the remote doesn't support the side-band, we can feed * the data directly to the pack writer. Otherwise, we need to * check which one belongs there. */ if (!t->caps.side_band && !t->caps.side_band_64k) { error = no_sideband(t, writepack, buf, stats); goto done; } do { git_pkt *pkt = NULL; /* Check cancellation before network call */ if (t->cancelled.val) { git_error_clear(); error = GIT_EUSER; goto done; } if ((error = recv_pkt(&pkt, NULL, buf)) >= 0) { /* Check cancellation after network call */ if (t->cancelled.val) { git_error_clear(); error = GIT_EUSER; } else if (pkt->type == GIT_PKT_PROGRESS) { if (t->progress_cb) { git_pkt_progress *p = (git_pkt_progress *) pkt; if (p->len > INT_MAX) { git_error_set(GIT_ERROR_NET, "oversized progress message"); error = GIT_ERROR; goto done; } error = t->progress_cb(p->data, (int)p->len, t->message_cb_payload); } } else if (pkt->type == GIT_PKT_DATA) { git_pkt_data *p = (git_pkt_data *) pkt; if (p->len) error = writepack->append(writepack, p->data, p->len, stats); } else if (pkt->type == GIT_PKT_FLUSH) { /* A flush indicates the end of the packfile */ git__free(pkt); break; } } git_pkt_free(pkt); if (error < 0) goto done; } while (1); /* * Trailing execution of progress_cb, if necessary... * Only the callback through the npp datastructure currently * updates the last_fired_bytes value. It is possible that * progress has already been reported with the correct * "received_bytes" value, but until (if?) this is unified * then we will report progress again to be sure that the * correct last received_bytes value is reported. */ if (npp.callback && npp.stats->received_bytes > npp.last_fired_bytes) { error = npp.callback(npp.stats, npp.payload); if (error != 0) goto done; } error = writepack->commit(writepack, stats); done: if (writepack) writepack->free(writepack); if (progress_cb) { t->packetsize_cb = NULL; t->packetsize_payload = NULL; } return error; } static int gen_pktline(git_buf *buf, git_push *push) { push_spec *spec; size_t i, len; char old_id[GIT_OID_HEXSZ+1], new_id[GIT_OID_HEXSZ+1]; old_id[GIT_OID_HEXSZ] = '\0'; new_id[GIT_OID_HEXSZ] = '\0'; git_vector_foreach(&push->specs, i, spec) { len = 2*GIT_OID_HEXSZ + 7 + strlen(spec->refspec.dst); if (i == 0) { ++len; /* '\0' */ if (push->report_status) len += strlen(GIT_CAP_REPORT_STATUS) + 1; len += strlen(GIT_CAP_SIDE_BAND_64K) + 1; } git_oid_fmt(old_id, &spec->roid); git_oid_fmt(new_id, &spec->loid); git_buf_printf(buf, "%04"PRIxZ"%s %s %s", len, old_id, new_id, spec->refspec.dst); if (i == 0) { git_buf_putc(buf, '\0'); /* Core git always starts their capabilities string with a space */ if (push->report_status) { git_buf_putc(buf, ' '); git_buf_printf(buf, GIT_CAP_REPORT_STATUS); } git_buf_putc(buf, ' '); git_buf_printf(buf, GIT_CAP_SIDE_BAND_64K); } git_buf_putc(buf, '\n'); } git_buf_puts(buf, "0000"); return git_buf_oom(buf) ? -1 : 0; } static int add_push_report_pkt(git_push *push, git_pkt *pkt) { push_status *status; switch (pkt->type) { case GIT_PKT_OK: status = git__calloc(1, sizeof(push_status)); GIT_ERROR_CHECK_ALLOC(status); status->msg = NULL; status->ref = git__strdup(((git_pkt_ok *)pkt)->ref); if (!status->ref || git_vector_insert(&push->status, status) < 0) { git_push_status_free(status); return -1; } break; case GIT_PKT_NG: status = git__calloc(1, sizeof(push_status)); GIT_ERROR_CHECK_ALLOC(status); status->ref = git__strdup(((git_pkt_ng *)pkt)->ref); status->msg = git__strdup(((git_pkt_ng *)pkt)->msg); if (!status->ref || !status->msg || git_vector_insert(&push->status, status) < 0) { git_push_status_free(status); return -1; } break; case GIT_PKT_UNPACK: push->unpack_ok = ((git_pkt_unpack *)pkt)->unpack_ok; break; case GIT_PKT_FLUSH: return GIT_ITEROVER; default: git_error_set(GIT_ERROR_NET, "report-status: protocol error"); return -1; } return 0; } static int add_push_report_sideband_pkt(git_push *push, git_pkt_data *data_pkt, git_buf *data_pkt_buf) { git_pkt *pkt; const char *line, *line_end = NULL; size_t line_len; int error; int reading_from_buf = data_pkt_buf->size > 0; if (reading_from_buf) { /* We had an existing partial packet, so add the new * packet to the buffer and parse the whole thing */ git_buf_put(data_pkt_buf, data_pkt->data, data_pkt->len); line = data_pkt_buf->ptr; line_len = data_pkt_buf->size; } else { line = data_pkt->data; line_len = data_pkt->len; } while (line_len > 0) { error = git_pkt_parse_line(&pkt, &line_end, line, line_len); if (error == GIT_EBUFS) { /* Buffer the data when the inner packet is split * across multiple sideband packets */ if (!reading_from_buf) git_buf_put(data_pkt_buf, line, line_len); error = 0; goto done; } else if (error < 0) goto done; /* Advance in the buffer */ line_len -= (line_end - line); line = line_end; error = add_push_report_pkt(push, pkt); git_pkt_free(pkt); if (error < 0 && error != GIT_ITEROVER) goto done; } error = 0; done: if (reading_from_buf) git_buf_consume(data_pkt_buf, line_end); return error; } static int parse_report(transport_smart *transport, git_push *push) { git_pkt *pkt = NULL; const char *line_end = NULL; gitno_buffer *buf = &transport->buffer; int error, recvd; git_buf data_pkt_buf = GIT_BUF_INIT; for (;;) { if (buf->offset > 0) error = git_pkt_parse_line(&pkt, &line_end, buf->data, buf->offset); else error = GIT_EBUFS; if (error < 0 && error != GIT_EBUFS) { error = -1; goto done; } if (error == GIT_EBUFS) { if ((recvd = gitno_recv(buf)) < 0) { error = recvd; goto done; } if (recvd == 0) { git_error_set(GIT_ERROR_NET, "early EOF"); error = GIT_EEOF; goto done; } continue; } if (gitno_consume(buf, line_end) < 0) return -1; error = 0; switch (pkt->type) { case GIT_PKT_DATA: /* This is a sideband packet which contains other packets */ error = add_push_report_sideband_pkt(push, (git_pkt_data *)pkt, &data_pkt_buf); break; case GIT_PKT_ERR: git_error_set(GIT_ERROR_NET, "report-status: Error reported: %s", ((git_pkt_err *)pkt)->error); error = -1; break; case GIT_PKT_PROGRESS: if (transport->progress_cb) { git_pkt_progress *p = (git_pkt_progress *) pkt; if (p->len > INT_MAX) { git_error_set(GIT_ERROR_NET, "oversized progress message"); error = GIT_ERROR; goto done; } error = transport->progress_cb(p->data, (int)p->len, transport->message_cb_payload); } break; default: error = add_push_report_pkt(push, pkt); break; } git_pkt_free(pkt); /* add_push_report_pkt returns GIT_ITEROVER when it receives a flush */ if (error == GIT_ITEROVER) { error = 0; if (data_pkt_buf.size > 0) { /* If there was data remaining in the pack data buffer, * then the server sent a partial pkt-line */ git_error_set(GIT_ERROR_NET, "incomplete pack data pkt-line"); error = GIT_ERROR; } goto done; } if (error < 0) { goto done; } } done: git_buf_dispose(&data_pkt_buf); return error; } static int add_ref_from_push_spec(git_vector *refs, push_spec *push_spec) { git_pkt_ref *added = git__calloc(1, sizeof(git_pkt_ref)); GIT_ERROR_CHECK_ALLOC(added); added->type = GIT_PKT_REF; git_oid_cpy(&added->head.oid, &push_spec->loid); added->head.name = git__strdup(push_spec->refspec.dst); if (!added->head.name || git_vector_insert(refs, added) < 0) { git_pkt_free((git_pkt *)added); return -1; } return 0; } static int update_refs_from_report( git_vector *refs, git_vector *push_specs, git_vector *push_report) { git_pkt_ref *ref; push_spec *push_spec; push_status *push_status; size_t i, j, refs_len; int cmp; /* For each push spec we sent to the server, we should have * gotten back a status packet in the push report */ if (push_specs->length != push_report->length) { git_error_set(GIT_ERROR_NET, "report-status: protocol error"); return -1; } /* We require that push_specs be sorted with push_spec_rref_cmp, * and that push_report be sorted with push_status_ref_cmp */ git_vector_sort(push_specs); git_vector_sort(push_report); git_vector_foreach(push_specs, i, push_spec) { push_status = git_vector_get(push_report, i); /* For each push spec we sent to the server, we should have * gotten back a status packet in the push report which matches */ if (strcmp(push_spec->refspec.dst, push_status->ref)) { git_error_set(GIT_ERROR_NET, "report-status: protocol error"); return -1; } } /* We require that refs be sorted with ref_name_cmp */ git_vector_sort(refs); i = j = 0; refs_len = refs->length; /* Merge join push_specs with refs */ while (i < push_specs->length && j < refs_len) { push_spec = git_vector_get(push_specs, i); push_status = git_vector_get(push_report, i); ref = git_vector_get(refs, j); cmp = strcmp(push_spec->refspec.dst, ref->head.name); /* Iterate appropriately */ if (cmp <= 0) i++; if (cmp >= 0) j++; /* Add case */ if (cmp < 0 && !push_status->msg && add_ref_from_push_spec(refs, push_spec) < 0) return -1; /* Update case, delete case */ if (cmp == 0 && !push_status->msg) git_oid_cpy(&ref->head.oid, &push_spec->loid); } for (; i < push_specs->length; i++) { push_spec = git_vector_get(push_specs, i); push_status = git_vector_get(push_report, i); /* Add case */ if (!push_status->msg && add_ref_from_push_spec(refs, push_spec) < 0) return -1; } /* Remove any refs which we updated to have a zero OID. */ git_vector_rforeach(refs, i, ref) { if (git_oid_is_zero(&ref->head.oid)) { git_vector_remove(refs, i); git_pkt_free((git_pkt *)ref); } } git_vector_sort(refs); return 0; } struct push_packbuilder_payload { git_smart_subtransport_stream *stream; git_packbuilder *pb; git_push_transfer_progress_cb cb; void *cb_payload; size_t last_bytes; double last_progress_report_time; }; static int stream_thunk(void *buf, size_t size, void *data) { int error = 0; struct push_packbuilder_payload *payload = data; if ((error = payload->stream->write(payload->stream, (const char *)buf, size)) < 0) return error; if (payload->cb) { double current_time = git__timer(); double elapsed = current_time - payload->last_progress_report_time; payload->last_bytes += size; if (elapsed < 0 || elapsed >= MIN_PROGRESS_UPDATE_INTERVAL) { payload->last_progress_report_time = current_time; error = payload->cb(payload->pb->nr_written, payload->pb->nr_objects, payload->last_bytes, payload->cb_payload); } } return error; } int git_smart__push(git_transport *transport, git_push *push, const git_remote_callbacks *cbs) { transport_smart *t = (transport_smart *)transport; struct push_packbuilder_payload packbuilder_payload = {0}; git_buf pktline = GIT_BUF_INIT; int error = 0, need_pack = 0; push_spec *spec; unsigned int i; packbuilder_payload.pb = push->pb; if (cbs && cbs->push_transfer_progress) { packbuilder_payload.cb = cbs->push_transfer_progress; packbuilder_payload.cb_payload = cbs->payload; } #ifdef PUSH_DEBUG { git_remote_head *head; char hex[GIT_OID_HEXSZ+1]; hex[GIT_OID_HEXSZ] = '\0'; git_vector_foreach(&push->remote->refs, i, head) { git_oid_fmt(hex, &head->oid); fprintf(stderr, "%s (%s)\n", hex, head->name); } git_vector_foreach(&push->specs, i, spec) { git_oid_fmt(hex, &spec->roid); fprintf(stderr, "%s (%s) -> ", hex, spec->lref); git_oid_fmt(hex, &spec->loid); fprintf(stderr, "%s (%s)\n", hex, spec->rref ? spec->rref : spec->lref); } } #endif /* * Figure out if we need to send a packfile; which is in all * cases except when we only send delete commands */ git_vector_foreach(&push->specs, i, spec) { if (spec->refspec.src && spec->refspec.src[0] != '\0') { need_pack = 1; break; } } if ((error = git_smart__get_push_stream(t, &packbuilder_payload.stream)) < 0 || (error = gen_pktline(&pktline, push)) < 0 || (error = packbuilder_payload.stream->write(packbuilder_payload.stream, git_buf_cstr(&pktline), git_buf_len(&pktline))) < 0) goto done; if (need_pack && (error = git_packbuilder_foreach(push->pb, &stream_thunk, &packbuilder_payload)) < 0) goto done; /* If we sent nothing or the server doesn't support report-status, then * we consider the pack to have been unpacked successfully */ if (!push->specs.length || !push->report_status) push->unpack_ok = 1; else if ((error = parse_report(t, push)) < 0) goto done; /* If progress is being reported write the final report */ if (cbs && cbs->push_transfer_progress) { error = cbs->push_transfer_progress( push->pb->nr_written, push->pb->nr_objects, packbuilder_payload.last_bytes, cbs->payload); if (error < 0) goto done; } if (push->status.length) { error = update_refs_from_report(&t->refs, &push->specs, &push->status); if (error < 0) goto done; error = git_smart__update_heads(t, NULL); } done: git_buf_dispose(&pktline); return error; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/transports/httpclient.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_transports_httpclient_h__ #define INCLUDE_transports_httpclient_h__ #include "common.h" #include "net.h" #define GIT_HTTP_STATUS_CONTINUE 100 #define GIT_HTTP_STATUS_OK 200 #define GIT_HTTP_MOVED_PERMANENTLY 301 #define GIT_HTTP_FOUND 302 #define GIT_HTTP_SEE_OTHER 303 #define GIT_HTTP_TEMPORARY_REDIRECT 307 #define GIT_HTTP_PERMANENT_REDIRECT 308 #define GIT_HTTP_STATUS_UNAUTHORIZED 401 #define GIT_HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED 407 typedef struct git_http_client git_http_client; /** Method for the HTTP request */ typedef enum { GIT_HTTP_METHOD_GET, GIT_HTTP_METHOD_POST, GIT_HTTP_METHOD_CONNECT } git_http_method; /** An HTTP request */ typedef struct { git_http_method method; /**< Method for the request */ git_net_url *url; /**< Full request URL */ git_net_url *proxy; /**< Proxy to use */ /* Headers */ const char *accept; /**< Contents of the Accept header */ const char *content_type; /**< Content-Type header (for POST) */ git_credential *credentials; /**< Credentials to authenticate with */ git_credential *proxy_credentials; /**< Credentials for proxy */ git_strarray *custom_headers; /**< Additional headers to deliver */ /* To POST a payload, either set content_length OR set chunked. */ size_t content_length; /**< Length of the POST body */ unsigned chunked : 1, /**< Post with chunking */ expect_continue : 1; /**< Use expect/continue negotiation */ } git_http_request; typedef struct { int status; /* Headers */ char *content_type; size_t content_length; char *location; /* Authentication headers */ unsigned server_auth_schemetypes; /**< Schemes requested by remote */ unsigned server_auth_credtypes; /**< Supported cred types for remote */ unsigned proxy_auth_schemetypes; /**< Schemes requested by proxy */ unsigned proxy_auth_credtypes; /**< Supported cred types for proxy */ unsigned chunked : 1, /**< Response body is chunked */ resend_credentials : 1; /**< Resend with authentication */ } git_http_response; typedef struct { /** Certificate check callback for the remote */ git_transport_certificate_check_cb server_certificate_check_cb; void *server_certificate_check_payload; /** Certificate check callback for the proxy */ git_transport_certificate_check_cb proxy_certificate_check_cb; void *proxy_certificate_check_payload; } git_http_client_options; /** * Create a new httpclient instance with the given options. * * @param out pointer to receive the new instance * @param opts options to create the client with or NULL for defaults */ extern int git_http_client_new( git_http_client **out, git_http_client_options *opts); /* * Sends a request to the host specified by the request URL. If the * method is POST, either the content_length or the chunked flag must * be specified. The body should be provided in subsequent calls to * git_http_client_send_body. * * @param client the client to write the request to * @param request the request to send */ extern int git_http_client_send_request( git_http_client *client, git_http_request *request); /* * After sending a request, there may already be a response to read -- * either because there was a non-continue response to an expect: continue * request, or because the server pipelined a response to us before we even * sent the request. Examine the state. * * @param client the client to examine * @return true if there's already a response to read, false otherwise */ extern bool git_http_client_has_response(git_http_client *client); /** * Sends the given buffer to the remote as part of the request body. The * request must have specified either a content_length or the chunked flag. * * @param client the client to write the request body to * @param buffer the request body * @param buffer_len number of bytes of the buffer to send */ extern int git_http_client_send_body( git_http_client *client, const char *buffer, size_t buffer_len); /** * Reads the headers of a response to a request. This will consume the * entirety of the headers of a response from the server. The body (if any) * can be read by calling git_http_client_read_body. Callers must free * the response with git_http_response_dispose. * * @param response pointer to the response object to fill * @param client the client to read the response from */ extern int git_http_client_read_response( git_http_response *response, git_http_client *client); /** * Reads some or all of the body of a response. At most buffer_size (or * INT_MAX) bytes will be read and placed into the buffer provided. The * number of bytes read will be returned, or 0 to indicate that the end of * the body has been read. * * @param client the client to read the response from * @param buffer pointer to the buffer to fill * @param buffer_size the maximum number of bytes to read * @return the number of bytes read, 0 on end of body, or error code */ extern int git_http_client_read_body( git_http_client *client, char *buffer, size_t buffer_size); /** * Reads all of the (remainder of the) body of the response and ignores it. * None of the data from the body will be returned to the caller. * * @param client the client to read the response from * @return 0 or an error code */ extern int git_http_client_skip_body(git_http_client *client); /** * Examines the status code of the response to determine if it is a * redirect of any type (eg, 301, 302, etc). * * @param response the response to inspect * @return true if the response is a redirect, false otherwise */ extern bool git_http_response_is_redirect(git_http_response *response); /** * Frees any memory associated with the response. * * @param response the response to free */ extern void git_http_response_dispose(git_http_response *response); /** * Frees any memory associated with the client. If any sockets are open, * they will be closed. * * @param client the client to free */ extern void git_http_client_free(git_http_client *client); #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/transports/ssh.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "ssh.h" #ifdef GIT_SSH #include <libssh2.h> #endif #include "runtime.h" #include "git2.h" #include "buffer.h" #include "net.h" #include "netops.h" #include "smart.h" #include "streams/socket.h" #include "git2/credential.h" #include "git2/sys/credential.h" #ifdef GIT_SSH #define OWNING_SUBTRANSPORT(s) ((ssh_subtransport *)(s)->parent.subtransport) static const char *ssh_prefixes[] = { "ssh://", "ssh+git://", "git+ssh://" }; static const char cmd_uploadpack[] = "git-upload-pack"; static const char cmd_receivepack[] = "git-receive-pack"; typedef struct { git_smart_subtransport_stream parent; git_stream *io; LIBSSH2_SESSION *session; LIBSSH2_CHANNEL *channel; const char *cmd; char *url; unsigned sent_command : 1; } ssh_stream; typedef struct { git_smart_subtransport parent; transport_smart *owner; ssh_stream *current_stream; git_credential *cred; char *cmd_uploadpack; char *cmd_receivepack; } ssh_subtransport; static int list_auth_methods(int *out, LIBSSH2_SESSION *session, const char *username); static void ssh_error(LIBSSH2_SESSION *session, const char *errmsg) { char *ssherr; libssh2_session_last_error(session, &ssherr, NULL, 0); git_error_set(GIT_ERROR_SSH, "%s: %s", errmsg, ssherr); } /* * Create a git protocol request. * * For example: git-upload-pack '/libgit2/libgit2' */ static int gen_proto(git_buf *request, const char *cmd, const char *url) { const char *repo; int len; size_t i; for (i = 0; i < ARRAY_SIZE(ssh_prefixes); ++i) { const char *p = ssh_prefixes[i]; if (!git__prefixcmp(url, p)) { url = url + strlen(p); repo = strchr(url, '/'); if (repo && repo[1] == '~') ++repo; goto done; } } repo = strchr(url, ':'); if (repo) repo++; done: if (!repo) { git_error_set(GIT_ERROR_NET, "malformed git protocol URL"); return -1; } len = strlen(cmd) + 1 /* Space */ + 1 /* Quote */ + strlen(repo) + 1 /* Quote */ + 1; git_buf_grow(request, len); git_buf_puts(request, cmd); git_buf_puts(request, " '"); git_buf_decode_percent(request, repo, strlen(repo)); git_buf_puts(request, "'"); if (git_buf_oom(request)) return -1; return 0; } static int send_command(ssh_stream *s) { int error; git_buf request = GIT_BUF_INIT; error = gen_proto(&request, s->cmd, s->url); if (error < 0) goto cleanup; error = libssh2_channel_exec(s->channel, request.ptr); if (error < LIBSSH2_ERROR_NONE) { ssh_error(s->session, "SSH could not execute request"); goto cleanup; } s->sent_command = 1; cleanup: git_buf_dispose(&request); return error; } static int ssh_stream_read( git_smart_subtransport_stream *stream, char *buffer, size_t buf_size, size_t *bytes_read) { int rc; ssh_stream *s = GIT_CONTAINER_OF(stream, ssh_stream, parent); *bytes_read = 0; if (!s->sent_command && send_command(s) < 0) return -1; if ((rc = libssh2_channel_read(s->channel, buffer, buf_size)) < LIBSSH2_ERROR_NONE) { ssh_error(s->session, "SSH could not read data"); return -1; } /* * If we can't get anything out of stdout, it's typically a * not-found error, so read from stderr and signal EOF on * stderr. */ if (rc == 0) { if ((rc = libssh2_channel_read_stderr(s->channel, buffer, buf_size)) > 0) { git_error_set(GIT_ERROR_SSH, "%*s", rc, buffer); return GIT_EEOF; } else if (rc < LIBSSH2_ERROR_NONE) { ssh_error(s->session, "SSH could not read stderr"); return -1; } } *bytes_read = rc; return 0; } static int ssh_stream_write( git_smart_subtransport_stream *stream, const char *buffer, size_t len) { ssh_stream *s = GIT_CONTAINER_OF(stream, ssh_stream, parent); size_t off = 0; ssize_t ret = 0; if (!s->sent_command && send_command(s) < 0) return -1; do { ret = libssh2_channel_write(s->channel, buffer + off, len - off); if (ret < 0) break; off += ret; } while (off < len); if (ret < 0) { ssh_error(s->session, "SSH could not write data"); return -1; } return 0; } static void ssh_stream_free(git_smart_subtransport_stream *stream) { ssh_stream *s = GIT_CONTAINER_OF(stream, ssh_stream, parent); ssh_subtransport *t; if (!stream) return; t = OWNING_SUBTRANSPORT(s); t->current_stream = NULL; if (s->channel) { libssh2_channel_close(s->channel); libssh2_channel_free(s->channel); s->channel = NULL; } if (s->session) { libssh2_session_disconnect(s->session, "closing transport"); libssh2_session_free(s->session); s->session = NULL; } if (s->io) { git_stream_close(s->io); git_stream_free(s->io); s->io = NULL; } git__free(s->url); git__free(s); } static int ssh_stream_alloc( ssh_subtransport *t, const char *url, const char *cmd, git_smart_subtransport_stream **stream) { ssh_stream *s; GIT_ASSERT_ARG(stream); s = git__calloc(sizeof(ssh_stream), 1); GIT_ERROR_CHECK_ALLOC(s); s->parent.subtransport = &t->parent; s->parent.read = ssh_stream_read; s->parent.write = ssh_stream_write; s->parent.free = ssh_stream_free; s->cmd = cmd; s->url = git__strdup(url); if (!s->url) { git__free(s); return -1; } *stream = &s->parent; return 0; } static int git_ssh_extract_url_parts( git_net_url *urldata, const char *url) { char *colon, *at; const char *start; colon = strchr(url, ':'); at = strchr(url, '@'); if (at) { start = at + 1; urldata->username = git__substrdup(url, at - url); GIT_ERROR_CHECK_ALLOC(urldata->username); } else { start = url; urldata->username = NULL; } if (colon == NULL || (colon < start)) { git_error_set(GIT_ERROR_NET, "malformed URL"); return -1; } urldata->host = git__substrdup(start, colon - start); GIT_ERROR_CHECK_ALLOC(urldata->host); return 0; } static int ssh_agent_auth(LIBSSH2_SESSION *session, git_credential_ssh_key *c) { int rc = LIBSSH2_ERROR_NONE; struct libssh2_agent_publickey *curr, *prev = NULL; LIBSSH2_AGENT *agent = libssh2_agent_init(session); if (agent == NULL) return -1; rc = libssh2_agent_connect(agent); if (rc != LIBSSH2_ERROR_NONE) goto shutdown; rc = libssh2_agent_list_identities(agent); if (rc != LIBSSH2_ERROR_NONE) goto shutdown; while (1) { rc = libssh2_agent_get_identity(agent, &curr, prev); if (rc < 0) goto shutdown; /* rc is set to 1 whenever the ssh agent ran out of keys to check. * Set the error code to authentication failure rather than erroring * out with an untranslatable error code. */ if (rc == 1) { rc = LIBSSH2_ERROR_AUTHENTICATION_FAILED; goto shutdown; } rc = libssh2_agent_userauth(agent, c->username, curr); if (rc == 0) break; prev = curr; } shutdown: if (rc != LIBSSH2_ERROR_NONE) ssh_error(session, "error authenticating"); libssh2_agent_disconnect(agent); libssh2_agent_free(agent); return rc; } static int _git_ssh_authenticate_session( LIBSSH2_SESSION *session, git_credential *cred) { int rc; do { git_error_clear(); switch (cred->credtype) { case GIT_CREDENTIAL_USERPASS_PLAINTEXT: { git_credential_userpass_plaintext *c = (git_credential_userpass_plaintext *)cred; rc = libssh2_userauth_password(session, c->username, c->password); break; } case GIT_CREDENTIAL_SSH_KEY: { git_credential_ssh_key *c = (git_credential_ssh_key *)cred; if (c->privatekey) rc = libssh2_userauth_publickey_fromfile( session, c->username, c->publickey, c->privatekey, c->passphrase); else rc = ssh_agent_auth(session, c); break; } case GIT_CREDENTIAL_SSH_CUSTOM: { git_credential_ssh_custom *c = (git_credential_ssh_custom *)cred; rc = libssh2_userauth_publickey( session, c->username, (const unsigned char *)c->publickey, c->publickey_len, c->sign_callback, &c->payload); break; } case GIT_CREDENTIAL_SSH_INTERACTIVE: { void **abstract = libssh2_session_abstract(session); git_credential_ssh_interactive *c = (git_credential_ssh_interactive *)cred; /* ideally, we should be able to set this by calling * libssh2_session_init_ex() instead of libssh2_session_init(). * libssh2's API is inconsistent here i.e. libssh2_userauth_publickey() * allows you to pass the `abstract` as part of the call, whereas * libssh2_userauth_keyboard_interactive() does not! * * The only way to set the `abstract` pointer is by calling * libssh2_session_abstract(), which will replace the existing * pointer as is done below. This is safe for now (at time of writing), * but may not be valid in future. */ *abstract = c->payload; rc = libssh2_userauth_keyboard_interactive( session, c->username, c->prompt_callback); break; } #ifdef GIT_SSH_MEMORY_CREDENTIALS case GIT_CREDENTIAL_SSH_MEMORY: { git_credential_ssh_key *c = (git_credential_ssh_key *)cred; GIT_ASSERT(c->username); GIT_ASSERT(c->privatekey); rc = libssh2_userauth_publickey_frommemory( session, c->username, strlen(c->username), c->publickey, c->publickey ? strlen(c->publickey) : 0, c->privatekey, strlen(c->privatekey), c->passphrase); break; } #endif default: rc = LIBSSH2_ERROR_AUTHENTICATION_FAILED; } } while (LIBSSH2_ERROR_EAGAIN == rc || LIBSSH2_ERROR_TIMEOUT == rc); if (rc == LIBSSH2_ERROR_PASSWORD_EXPIRED || rc == LIBSSH2_ERROR_AUTHENTICATION_FAILED || rc == LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED) return GIT_EAUTH; if (rc != LIBSSH2_ERROR_NONE) { if (!git_error_last()) ssh_error(session, "Failed to authenticate SSH session"); return -1; } return 0; } static int request_creds(git_credential **out, ssh_subtransport *t, const char *user, int auth_methods) { int error, no_callback = 0; git_credential *cred = NULL; if (!t->owner->cred_acquire_cb) { no_callback = 1; } else { error = t->owner->cred_acquire_cb(&cred, t->owner->url, user, auth_methods, t->owner->cred_acquire_payload); if (error == GIT_PASSTHROUGH) { no_callback = 1; } else if (error < 0) { return error; } else if (!cred) { git_error_set(GIT_ERROR_SSH, "callback failed to initialize SSH credentials"); return -1; } } if (no_callback) { git_error_set(GIT_ERROR_SSH, "authentication required but no callback set"); return GIT_EAUTH; } if (!(cred->credtype & auth_methods)) { cred->free(cred); git_error_set(GIT_ERROR_SSH, "authentication callback returned unsupported credentials type"); return GIT_EAUTH; } *out = cred; return 0; } static int _git_ssh_session_create( LIBSSH2_SESSION **session, git_stream *io) { int rc = 0; LIBSSH2_SESSION *s; git_socket_stream *socket = GIT_CONTAINER_OF(io, git_socket_stream, parent); GIT_ASSERT_ARG(session); s = libssh2_session_init(); if (!s) { git_error_set(GIT_ERROR_NET, "failed to initialize SSH session"); return -1; } do { rc = libssh2_session_handshake(s, socket->s); } while (LIBSSH2_ERROR_EAGAIN == rc || LIBSSH2_ERROR_TIMEOUT == rc); if (rc != LIBSSH2_ERROR_NONE) { ssh_error(s, "failed to start SSH session"); libssh2_session_free(s); return -1; } libssh2_session_set_blocking(s, 1); *session = s; return 0; } #define SSH_DEFAULT_PORT "22" static int _git_ssh_setup_conn( ssh_subtransport *t, const char *url, const char *cmd, git_smart_subtransport_stream **stream) { git_net_url urldata = GIT_NET_URL_INIT; int auth_methods, error = 0; size_t i; ssh_stream *s; git_credential *cred = NULL; LIBSSH2_SESSION *session=NULL; LIBSSH2_CHANNEL *channel=NULL; t->current_stream = NULL; *stream = NULL; if (ssh_stream_alloc(t, url, cmd, stream) < 0) return -1; s = (ssh_stream *)*stream; s->session = NULL; s->channel = NULL; for (i = 0; i < ARRAY_SIZE(ssh_prefixes); ++i) { const char *p = ssh_prefixes[i]; if (!git__prefixcmp(url, p)) { if ((error = git_net_url_parse(&urldata, url)) < 0) goto done; goto post_extract; } } if ((error = git_ssh_extract_url_parts(&urldata, url)) < 0) goto done; if (urldata.port == NULL) urldata.port = git__strdup(SSH_DEFAULT_PORT); GIT_ERROR_CHECK_ALLOC(urldata.port); post_extract: if ((error = git_socket_stream_new(&s->io, urldata.host, urldata.port)) < 0 || (error = git_stream_connect(s->io)) < 0) goto done; if ((error = _git_ssh_session_create(&session, s->io)) < 0) goto done; if (t->owner->certificate_check_cb != NULL) { git_cert_hostkey cert = {{ 0 }}, *cert_ptr; const char *key; size_t cert_len; int cert_type; cert.parent.cert_type = GIT_CERT_HOSTKEY_LIBSSH2; key = libssh2_session_hostkey(session, &cert_len, &cert_type); if (key != NULL) { cert.type |= GIT_CERT_SSH_RAW; cert.hostkey = key; cert.hostkey_len = cert_len; switch (cert_type) { case LIBSSH2_HOSTKEY_TYPE_RSA: cert.raw_type = GIT_CERT_SSH_RAW_TYPE_RSA; break; case LIBSSH2_HOSTKEY_TYPE_DSS: cert.raw_type = GIT_CERT_SSH_RAW_TYPE_DSS; break; #ifdef LIBSSH2_HOSTKEY_TYPE_ECDSA_256 case LIBSSH2_HOSTKEY_TYPE_ECDSA_256: cert.raw_type = GIT_CERT_SSH_RAW_TYPE_KEY_ECDSA_256; break; case LIBSSH2_HOSTKEY_TYPE_ECDSA_384: cert.raw_type = GIT_CERT_SSH_RAW_TYPE_KEY_ECDSA_384; break; case LIBSSH2_KNOWNHOST_KEY_ECDSA_521: cert.raw_type = GIT_CERT_SSH_RAW_TYPE_KEY_ECDSA_521; break; #endif #ifdef LIBSSH2_HOSTKEY_TYPE_ED25519 case LIBSSH2_HOSTKEY_TYPE_ED25519: cert.raw_type = GIT_CERT_SSH_RAW_TYPE_KEY_ED25519; break; #endif default: cert.raw_type = GIT_CERT_SSH_RAW_TYPE_UNKNOWN; } } #ifdef LIBSSH2_HOSTKEY_HASH_SHA256 key = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA256); if (key != NULL) { cert.type |= GIT_CERT_SSH_SHA256; memcpy(&cert.hash_sha256, key, 32); } #endif key = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1); if (key != NULL) { cert.type |= GIT_CERT_SSH_SHA1; memcpy(&cert.hash_sha1, key, 20); } key = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_MD5); if (key != NULL) { cert.type |= GIT_CERT_SSH_MD5; memcpy(&cert.hash_md5, key, 16); } if (cert.type == 0) { git_error_set(GIT_ERROR_SSH, "unable to get the host key"); error = -1; goto done; } /* We don't currently trust any hostkeys */ git_error_clear(); cert_ptr = &cert; error = t->owner->certificate_check_cb((git_cert *) cert_ptr, 0, urldata.host, t->owner->message_cb_payload); if (error < 0 && error != GIT_PASSTHROUGH) { if (!git_error_last()) git_error_set(GIT_ERROR_NET, "user cancelled hostkey check"); goto done; } } /* we need the username to ask for auth methods */ if (!urldata.username) { if ((error = request_creds(&cred, t, NULL, GIT_CREDENTIAL_USERNAME)) < 0) goto done; urldata.username = git__strdup(((git_credential_username *) cred)->username); cred->free(cred); cred = NULL; if (!urldata.username) goto done; } else if (urldata.username && urldata.password) { if ((error = git_credential_userpass_plaintext_new(&cred, urldata.username, urldata.password)) < 0) goto done; } if ((error = list_auth_methods(&auth_methods, session, urldata.username)) < 0) goto done; error = GIT_EAUTH; /* if we already have something to try */ if (cred && auth_methods & cred->credtype) error = _git_ssh_authenticate_session(session, cred); while (error == GIT_EAUTH) { if (cred) { cred->free(cred); cred = NULL; } if ((error = request_creds(&cred, t, urldata.username, auth_methods)) < 0) goto done; if (strcmp(urldata.username, git_credential_get_username(cred))) { git_error_set(GIT_ERROR_SSH, "username does not match previous request"); error = -1; goto done; } error = _git_ssh_authenticate_session(session, cred); if (error == GIT_EAUTH) { /* refresh auth methods */ if ((error = list_auth_methods(&auth_methods, session, urldata.username)) < 0) goto done; else error = GIT_EAUTH; } } if (error < 0) goto done; channel = libssh2_channel_open_session(session); if (!channel) { error = -1; ssh_error(session, "Failed to open SSH channel"); goto done; } libssh2_channel_set_blocking(channel, 1); s->session = session; s->channel = channel; t->current_stream = s; done: if (error < 0) { ssh_stream_free(*stream); if (session) libssh2_session_free(session); } if (cred) cred->free(cred); git_net_url_dispose(&urldata); return error; } static int ssh_uploadpack_ls( ssh_subtransport *t, const char *url, git_smart_subtransport_stream **stream) { const char *cmd = t->cmd_uploadpack ? t->cmd_uploadpack : cmd_uploadpack; return _git_ssh_setup_conn(t, url, cmd, stream); } static int ssh_uploadpack( ssh_subtransport *t, const char *url, git_smart_subtransport_stream **stream) { GIT_UNUSED(url); if (t->current_stream) { *stream = &t->current_stream->parent; return 0; } git_error_set(GIT_ERROR_NET, "must call UPLOADPACK_LS before UPLOADPACK"); return -1; } static int ssh_receivepack_ls( ssh_subtransport *t, const char *url, git_smart_subtransport_stream **stream) { const char *cmd = t->cmd_receivepack ? t->cmd_receivepack : cmd_receivepack; return _git_ssh_setup_conn(t, url, cmd, stream); } static int ssh_receivepack( ssh_subtransport *t, const char *url, git_smart_subtransport_stream **stream) { GIT_UNUSED(url); if (t->current_stream) { *stream = &t->current_stream->parent; return 0; } git_error_set(GIT_ERROR_NET, "must call RECEIVEPACK_LS before RECEIVEPACK"); return -1; } static int _ssh_action( git_smart_subtransport_stream **stream, git_smart_subtransport *subtransport, const char *url, git_smart_service_t action) { ssh_subtransport *t = GIT_CONTAINER_OF(subtransport, ssh_subtransport, parent); switch (action) { case GIT_SERVICE_UPLOADPACK_LS: return ssh_uploadpack_ls(t, url, stream); case GIT_SERVICE_UPLOADPACK: return ssh_uploadpack(t, url, stream); case GIT_SERVICE_RECEIVEPACK_LS: return ssh_receivepack_ls(t, url, stream); case GIT_SERVICE_RECEIVEPACK: return ssh_receivepack(t, url, stream); } *stream = NULL; return -1; } static int _ssh_close(git_smart_subtransport *subtransport) { ssh_subtransport *t = GIT_CONTAINER_OF(subtransport, ssh_subtransport, parent); GIT_ASSERT(!t->current_stream); GIT_UNUSED(t); return 0; } static void _ssh_free(git_smart_subtransport *subtransport) { ssh_subtransport *t = GIT_CONTAINER_OF(subtransport, ssh_subtransport, parent); git__free(t->cmd_uploadpack); git__free(t->cmd_receivepack); git__free(t); } #define SSH_AUTH_PUBLICKEY "publickey" #define SSH_AUTH_PASSWORD "password" #define SSH_AUTH_KEYBOARD_INTERACTIVE "keyboard-interactive" static int list_auth_methods(int *out, LIBSSH2_SESSION *session, const char *username) { const char *list, *ptr; *out = 0; list = libssh2_userauth_list(session, username, strlen(username)); /* either error, or the remote accepts NONE auth, which is bizarre, let's punt */ if (list == NULL && !libssh2_userauth_authenticated(session)) { ssh_error(session, "Failed to retrieve list of SSH authentication methods"); return GIT_EAUTH; } ptr = list; while (ptr) { if (*ptr == ',') ptr++; if (!git__prefixcmp(ptr, SSH_AUTH_PUBLICKEY)) { *out |= GIT_CREDENTIAL_SSH_KEY; *out |= GIT_CREDENTIAL_SSH_CUSTOM; #ifdef GIT_SSH_MEMORY_CREDENTIALS *out |= GIT_CREDENTIAL_SSH_MEMORY; #endif ptr += strlen(SSH_AUTH_PUBLICKEY); continue; } if (!git__prefixcmp(ptr, SSH_AUTH_PASSWORD)) { *out |= GIT_CREDENTIAL_USERPASS_PLAINTEXT; ptr += strlen(SSH_AUTH_PASSWORD); continue; } if (!git__prefixcmp(ptr, SSH_AUTH_KEYBOARD_INTERACTIVE)) { *out |= GIT_CREDENTIAL_SSH_INTERACTIVE; ptr += strlen(SSH_AUTH_KEYBOARD_INTERACTIVE); continue; } /* Skipt it if we don't know it */ ptr = strchr(ptr, ','); } return 0; } #endif int git_smart_subtransport_ssh( git_smart_subtransport **out, git_transport *owner, void *param) { #ifdef GIT_SSH ssh_subtransport *t; GIT_ASSERT_ARG(out); GIT_UNUSED(param); t = git__calloc(sizeof(ssh_subtransport), 1); GIT_ERROR_CHECK_ALLOC(t); t->owner = (transport_smart *)owner; t->parent.action = _ssh_action; t->parent.close = _ssh_close; t->parent.free = _ssh_free; *out = (git_smart_subtransport *) t; return 0; #else GIT_UNUSED(owner); GIT_UNUSED(param); GIT_ASSERT_ARG(out); *out = NULL; git_error_set(GIT_ERROR_INVALID, "cannot create SSH transport. Library was built without SSH support"); return -1; #endif } int git_transport_ssh_with_paths(git_transport **out, git_remote *owner, void *payload) { #ifdef GIT_SSH git_strarray *paths = (git_strarray *) payload; git_transport *transport; transport_smart *smart; ssh_subtransport *t; int error; git_smart_subtransport_definition ssh_definition = { git_smart_subtransport_ssh, 0, /* no RPC */ NULL, }; if (paths->count != 2) { git_error_set(GIT_ERROR_SSH, "invalid ssh paths, must be two strings"); return GIT_EINVALIDSPEC; } if ((error = git_transport_smart(&transport, owner, &ssh_definition)) < 0) return error; smart = (transport_smart *) transport; t = (ssh_subtransport *) smart->wrapped; t->cmd_uploadpack = git__strdup(paths->strings[0]); GIT_ERROR_CHECK_ALLOC(t->cmd_uploadpack); t->cmd_receivepack = git__strdup(paths->strings[1]); GIT_ERROR_CHECK_ALLOC(t->cmd_receivepack); *out = transport; return 0; #else GIT_UNUSED(owner); GIT_UNUSED(payload); GIT_ASSERT_ARG(out); *out = NULL; git_error_set(GIT_ERROR_INVALID, "cannot create SSH transport. Library was built without SSH support"); return -1; #endif } #ifdef GIT_SSH static void shutdown_ssh(void) { libssh2_exit(); } #endif int git_transport_ssh_global_init(void) { #ifdef GIT_SSH if (libssh2_init(0) < 0) { git_error_set(GIT_ERROR_SSH, "unable to initialize libssh2"); return -1; } return git_runtime_shutdown_register(shutdown_ssh); #else /* Nothing to initialize */ return 0; #endif }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/transports/credential.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "common.h" #include "git2/credential.h" #include "git2/sys/credential.h" #include "git2/credential_helpers.h" static int git_credential_ssh_key_type_new( git_credential **cred, const char *username, const char *publickey, const char *privatekey, const char *passphrase, git_credential_t credtype); int git_credential_has_username(git_credential *cred) { if (cred->credtype == GIT_CREDENTIAL_DEFAULT) return 0; return 1; } const char *git_credential_get_username(git_credential *cred) { switch (cred->credtype) { case GIT_CREDENTIAL_USERNAME: { git_credential_username *c = (git_credential_username *) cred; return c->username; } case GIT_CREDENTIAL_USERPASS_PLAINTEXT: { git_credential_userpass_plaintext *c = (git_credential_userpass_plaintext *) cred; return c->username; } case GIT_CREDENTIAL_SSH_KEY: case GIT_CREDENTIAL_SSH_MEMORY: { git_credential_ssh_key *c = (git_credential_ssh_key *) cred; return c->username; } case GIT_CREDENTIAL_SSH_CUSTOM: { git_credential_ssh_custom *c = (git_credential_ssh_custom *) cred; return c->username; } case GIT_CREDENTIAL_SSH_INTERACTIVE: { git_credential_ssh_interactive *c = (git_credential_ssh_interactive *) cred; return c->username; } default: return NULL; } } static void plaintext_free(struct git_credential *cred) { git_credential_userpass_plaintext *c = (git_credential_userpass_plaintext *)cred; git__free(c->username); /* Zero the memory which previously held the password */ if (c->password) { size_t pass_len = strlen(c->password); git__memzero(c->password, pass_len); git__free(c->password); } git__free(c); } int git_credential_userpass_plaintext_new( git_credential **cred, const char *username, const char *password) { git_credential_userpass_plaintext *c; GIT_ASSERT_ARG(cred); GIT_ASSERT_ARG(username); GIT_ASSERT_ARG(password); c = git__malloc(sizeof(git_credential_userpass_plaintext)); GIT_ERROR_CHECK_ALLOC(c); c->parent.credtype = GIT_CREDENTIAL_USERPASS_PLAINTEXT; c->parent.free = plaintext_free; c->username = git__strdup(username); if (!c->username) { git__free(c); return -1; } c->password = git__strdup(password); if (!c->password) { git__free(c->username); git__free(c); return -1; } *cred = &c->parent; return 0; } static void ssh_key_free(struct git_credential *cred) { git_credential_ssh_key *c = (git_credential_ssh_key *)cred; git__free(c->username); if (c->privatekey) { /* Zero the memory which previously held the private key */ size_t key_len = strlen(c->privatekey); git__memzero(c->privatekey, key_len); git__free(c->privatekey); } if (c->passphrase) { /* Zero the memory which previously held the passphrase */ size_t pass_len = strlen(c->passphrase); git__memzero(c->passphrase, pass_len); git__free(c->passphrase); } if (c->publickey) { /* Zero the memory which previously held the public key */ size_t key_len = strlen(c->publickey); git__memzero(c->publickey, key_len); git__free(c->publickey); } git__free(c); } static void ssh_interactive_free(struct git_credential *cred) { git_credential_ssh_interactive *c = (git_credential_ssh_interactive *)cred; git__free(c->username); git__free(c); } static void ssh_custom_free(struct git_credential *cred) { git_credential_ssh_custom *c = (git_credential_ssh_custom *)cred; git__free(c->username); if (c->publickey) { /* Zero the memory which previously held the publickey */ size_t key_len = strlen(c->publickey); git__memzero(c->publickey, key_len); git__free(c->publickey); } git__free(c); } static void default_free(struct git_credential *cred) { git_credential_default *c = (git_credential_default *)cred; git__free(c); } static void username_free(struct git_credential *cred) { git__free(cred); } int git_credential_ssh_key_new( git_credential **cred, const char *username, const char *publickey, const char *privatekey, const char *passphrase) { return git_credential_ssh_key_type_new( cred, username, publickey, privatekey, passphrase, GIT_CREDENTIAL_SSH_KEY); } int git_credential_ssh_key_memory_new( git_credential **cred, const char *username, const char *publickey, const char *privatekey, const char *passphrase) { #ifdef GIT_SSH_MEMORY_CREDENTIALS return git_credential_ssh_key_type_new( cred, username, publickey, privatekey, passphrase, GIT_CREDENTIAL_SSH_MEMORY); #else GIT_UNUSED(cred); GIT_UNUSED(username); GIT_UNUSED(publickey); GIT_UNUSED(privatekey); GIT_UNUSED(passphrase); git_error_set(GIT_ERROR_INVALID, "this version of libgit2 was not built with ssh memory credentials."); return -1; #endif } static int git_credential_ssh_key_type_new( git_credential **cred, const char *username, const char *publickey, const char *privatekey, const char *passphrase, git_credential_t credtype) { git_credential_ssh_key *c; GIT_ASSERT_ARG(username); GIT_ASSERT_ARG(cred); GIT_ASSERT_ARG(privatekey); c = git__calloc(1, sizeof(git_credential_ssh_key)); GIT_ERROR_CHECK_ALLOC(c); c->parent.credtype = credtype; c->parent.free = ssh_key_free; c->username = git__strdup(username); GIT_ERROR_CHECK_ALLOC(c->username); c->privatekey = git__strdup(privatekey); GIT_ERROR_CHECK_ALLOC(c->privatekey); if (publickey) { c->publickey = git__strdup(publickey); GIT_ERROR_CHECK_ALLOC(c->publickey); } if (passphrase) { c->passphrase = git__strdup(passphrase); GIT_ERROR_CHECK_ALLOC(c->passphrase); } *cred = &c->parent; return 0; } int git_credential_ssh_interactive_new( git_credential **out, const char *username, git_credential_ssh_interactive_cb prompt_callback, void *payload) { git_credential_ssh_interactive *c; GIT_ASSERT_ARG(out); GIT_ASSERT_ARG(username); GIT_ASSERT_ARG(prompt_callback); c = git__calloc(1, sizeof(git_credential_ssh_interactive)); GIT_ERROR_CHECK_ALLOC(c); c->parent.credtype = GIT_CREDENTIAL_SSH_INTERACTIVE; c->parent.free = ssh_interactive_free; c->username = git__strdup(username); GIT_ERROR_CHECK_ALLOC(c->username); c->prompt_callback = prompt_callback; c->payload = payload; *out = &c->parent; return 0; } int git_credential_ssh_key_from_agent(git_credential **cred, const char *username) { git_credential_ssh_key *c; GIT_ASSERT_ARG(username); GIT_ASSERT_ARG(cred); c = git__calloc(1, sizeof(git_credential_ssh_key)); GIT_ERROR_CHECK_ALLOC(c); c->parent.credtype = GIT_CREDENTIAL_SSH_KEY; c->parent.free = ssh_key_free; c->username = git__strdup(username); GIT_ERROR_CHECK_ALLOC(c->username); c->privatekey = NULL; *cred = &c->parent; return 0; } int git_credential_ssh_custom_new( git_credential **cred, const char *username, const char *publickey, size_t publickey_len, git_credential_sign_cb sign_callback, void *payload) { git_credential_ssh_custom *c; GIT_ASSERT_ARG(username); GIT_ASSERT_ARG(cred); c = git__calloc(1, sizeof(git_credential_ssh_custom)); GIT_ERROR_CHECK_ALLOC(c); c->parent.credtype = GIT_CREDENTIAL_SSH_CUSTOM; c->parent.free = ssh_custom_free; c->username = git__strdup(username); GIT_ERROR_CHECK_ALLOC(c->username); if (publickey_len > 0) { c->publickey = git__malloc(publickey_len); GIT_ERROR_CHECK_ALLOC(c->publickey); memcpy(c->publickey, publickey, publickey_len); } c->publickey_len = publickey_len; c->sign_callback = sign_callback; c->payload = payload; *cred = &c->parent; return 0; } int git_credential_default_new(git_credential **cred) { git_credential_default *c; GIT_ASSERT_ARG(cred); c = git__calloc(1, sizeof(git_credential_default)); GIT_ERROR_CHECK_ALLOC(c); c->credtype = GIT_CREDENTIAL_DEFAULT; c->free = default_free; *cred = c; return 0; } int git_credential_username_new(git_credential **cred, const char *username) { git_credential_username *c; size_t len, allocsize; GIT_ASSERT_ARG(cred); len = strlen(username); GIT_ERROR_CHECK_ALLOC_ADD(&allocsize, sizeof(git_credential_username), len); GIT_ERROR_CHECK_ALLOC_ADD(&allocsize, allocsize, 1); c = git__malloc(allocsize); GIT_ERROR_CHECK_ALLOC(c); c->parent.credtype = GIT_CREDENTIAL_USERNAME; c->parent.free = username_free; memcpy(c->username, username, len + 1); *cred = (git_credential *) c; return 0; } void git_credential_free(git_credential *cred) { if (!cred) return; cred->free(cred); } /* Deprecated credential functions */ #ifndef GIT_DEPRECATE_HARD int git_cred_has_username(git_credential *cred) { return git_credential_has_username(cred); } const char *git_cred_get_username(git_credential *cred) { return git_credential_get_username(cred); } int git_cred_userpass_plaintext_new( git_credential **out, const char *username, const char *password) { return git_credential_userpass_plaintext_new(out,username, password); } int git_cred_default_new(git_credential **out) { return git_credential_default_new(out); } int git_cred_username_new(git_credential **out, const char *username) { return git_credential_username_new(out, username); } int git_cred_ssh_key_new( git_credential **out, const char *username, const char *publickey, const char *privatekey, const char *passphrase) { return git_credential_ssh_key_new(out, username, publickey, privatekey, passphrase); } int git_cred_ssh_key_memory_new( git_credential **out, const char *username, const char *publickey, const char *privatekey, const char *passphrase) { return git_credential_ssh_key_memory_new(out, username, publickey, privatekey, passphrase); } int git_cred_ssh_interactive_new( git_credential **out, const char *username, git_credential_ssh_interactive_cb prompt_callback, void *payload) { return git_credential_ssh_interactive_new(out, username, prompt_callback, payload); } int git_cred_ssh_key_from_agent( git_credential **out, const char *username) { return git_credential_ssh_key_from_agent(out, username); } int git_cred_ssh_custom_new( git_credential **out, const char *username, const char *publickey, size_t publickey_len, git_credential_sign_cb sign_callback, void *payload) { return git_credential_ssh_custom_new(out, username, publickey, publickey_len, sign_callback, payload); } void git_cred_free(git_credential *cred) { git_credential_free(cred); } #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/transports/local.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "common.h" #include "git2/types.h" #include "git2/net.h" #include "git2/repository.h" #include "git2/object.h" #include "git2/tag.h" #include "git2/transport.h" #include "git2/revwalk.h" #include "git2/odb_backend.h" #include "git2/pack.h" #include "git2/commit.h" #include "git2/revparse.h" #include "pack-objects.h" #include "refs.h" #include "posix.h" #include "path.h" #include "buffer.h" #include "repository.h" #include "odb.h" #include "push.h" #include "remote.h" #include "proxy.h" typedef struct { git_transport parent; git_remote *owner; char *url; int direction; int flags; git_atomic32 cancelled; git_repository *repo; git_transport_message_cb progress_cb; git_transport_message_cb error_cb; void *message_cb_payload; git_vector refs; unsigned connected : 1, have_refs : 1; } transport_local; static void free_head(git_remote_head *head) { git__free(head->name); git__free(head->symref_target); git__free(head); } static void free_heads(git_vector *heads) { git_remote_head *head; size_t i; git_vector_foreach(heads, i, head) free_head(head); git_vector_free(heads); } static int add_ref(transport_local *t, const char *name) { const char peeled[] = "^{}"; git_reference *ref, *resolved; git_remote_head *head; git_oid obj_id; git_object *obj = NULL, *target = NULL; git_buf buf = GIT_BUF_INIT; int error; if ((error = git_reference_lookup(&ref, t->repo, name)) < 0) return error; error = git_reference_resolve(&resolved, ref); if (error < 0) { git_reference_free(ref); if (!strcmp(name, GIT_HEAD_FILE) && error == GIT_ENOTFOUND) { /* This is actually okay. Empty repos often have a HEAD that * points to a nonexistent "refs/heads/master". */ git_error_clear(); return 0; } return error; } git_oid_cpy(&obj_id, git_reference_target(resolved)); git_reference_free(resolved); head = git__calloc(1, sizeof(git_remote_head)); GIT_ERROR_CHECK_ALLOC(head); head->name = git__strdup(name); GIT_ERROR_CHECK_ALLOC(head->name); git_oid_cpy(&head->oid, &obj_id); if (git_reference_type(ref) == GIT_REFERENCE_SYMBOLIC) { head->symref_target = git__strdup(git_reference_symbolic_target(ref)); GIT_ERROR_CHECK_ALLOC(head->symref_target); } git_reference_free(ref); if ((error = git_vector_insert(&t->refs, head)) < 0) { free_head(head); return error; } /* If it's not a tag, we don't need to try to peel it */ if (git__prefixcmp(name, GIT_REFS_TAGS_DIR)) return 0; if ((error = git_object_lookup(&obj, t->repo, &head->oid, GIT_OBJECT_ANY)) < 0) return error; head = NULL; /* If it's not an annotated tag, or if we're mocking * git-receive-pack, just get out */ if (git_object_type(obj) != GIT_OBJECT_TAG || t->direction != GIT_DIRECTION_FETCH) { git_object_free(obj); return 0; } /* And if it's a tag, peel it, and add it to the list */ head = git__calloc(1, sizeof(git_remote_head)); GIT_ERROR_CHECK_ALLOC(head); if (git_buf_join(&buf, 0, name, peeled) < 0) { free_head(head); return -1; } head->name = git_buf_detach(&buf); if (!(error = git_tag_peel(&target, (git_tag *)obj))) { git_oid_cpy(&head->oid, git_object_id(target)); if ((error = git_vector_insert(&t->refs, head)) < 0) { free_head(head); } } git_object_free(obj); git_object_free(target); return error; } static int store_refs(transport_local *t) { size_t i; git_remote_head *head; git_strarray ref_names = {0}; GIT_ASSERT_ARG(t); if (git_reference_list(&ref_names, t->repo) < 0) goto on_error; /* Clear all heads we might have fetched in a previous connect */ git_vector_foreach(&t->refs, i, head) { git__free(head->name); git__free(head); } /* Clear the vector so we can reuse it */ git_vector_clear(&t->refs); /* Sort the references first */ git__tsort((void **)ref_names.strings, ref_names.count, &git__strcmp_cb); /* Add HEAD iff direction is fetch */ if (t->direction == GIT_DIRECTION_FETCH && add_ref(t, GIT_HEAD_FILE) < 0) goto on_error; for (i = 0; i < ref_names.count; ++i) { if (add_ref(t, ref_names.strings[i]) < 0) goto on_error; } t->have_refs = 1; git_strarray_dispose(&ref_names); return 0; on_error: git_vector_free(&t->refs); git_strarray_dispose(&ref_names); return -1; } /* * Try to open the url as a git directory. The direction doesn't * matter in this case because we're calculating the heads ourselves. */ static int local_connect( git_transport *transport, const char *url, git_credential_acquire_cb cred_acquire_cb, void *cred_acquire_payload, const git_proxy_options *proxy, int direction, int flags) { git_repository *repo; int error; transport_local *t = (transport_local *) transport; const char *path; git_buf buf = GIT_BUF_INIT; GIT_UNUSED(cred_acquire_cb); GIT_UNUSED(cred_acquire_payload); GIT_UNUSED(proxy); if (t->connected) return 0; free_heads(&t->refs); t->url = git__strdup(url); GIT_ERROR_CHECK_ALLOC(t->url); t->direction = direction; t->flags = flags; /* 'url' may be a url or path; convert to a path */ if ((error = git_path_from_url_or_path(&buf, url)) < 0) { git_buf_dispose(&buf); return error; } path = git_buf_cstr(&buf); error = git_repository_open(&repo, path); git_buf_dispose(&buf); if (error < 0) return -1; t->repo = repo; if (store_refs(t) < 0) return -1; t->connected = 1; return 0; } static int local_ls(const git_remote_head ***out, size_t *size, git_transport *transport) { transport_local *t = (transport_local *)transport; if (!t->have_refs) { git_error_set(GIT_ERROR_NET, "the transport has not yet loaded the refs"); return -1; } *out = (const git_remote_head **)t->refs.contents; *size = t->refs.length; return 0; } static int local_negotiate_fetch( git_transport *transport, git_repository *repo, const git_remote_head * const *refs, size_t count) { transport_local *t = (transport_local*)transport; git_remote_head *rhead; unsigned int i; GIT_UNUSED(refs); GIT_UNUSED(count); /* Fill in the loids */ git_vector_foreach(&t->refs, i, rhead) { git_object *obj; int error = git_revparse_single(&obj, repo, rhead->name); if (!error) git_oid_cpy(&rhead->loid, git_object_id(obj)); else if (error != GIT_ENOTFOUND) return error; else git_error_clear(); git_object_free(obj); } return 0; } static int local_push_update_remote_ref( git_repository *remote_repo, const char *lref, const char *rref, git_oid *loid, git_oid *roid) { int error; git_reference *remote_ref = NULL; /* check for lhs, if it's empty it means to delete */ if (lref[0] != '\0') { /* Create or update a ref */ error = git_reference_create(NULL, remote_repo, rref, loid, !git_oid_is_zero(roid), NULL); } else { /* Delete a ref */ if ((error = git_reference_lookup(&remote_ref, remote_repo, rref)) < 0) { if (error == GIT_ENOTFOUND) error = 0; return error; } error = git_reference_delete(remote_ref); git_reference_free(remote_ref); } return error; } static int transfer_to_push_transfer(const git_indexer_progress *stats, void *payload) { const git_remote_callbacks *cbs = payload; if (!cbs || !cbs->push_transfer_progress) return 0; return cbs->push_transfer_progress(stats->received_objects, stats->total_objects, stats->received_bytes, cbs->payload); } static int local_push( git_transport *transport, git_push *push, const git_remote_callbacks *cbs) { transport_local *t = (transport_local *)transport; git_repository *remote_repo = NULL; push_spec *spec; char *url = NULL; const char *path; git_buf buf = GIT_BUF_INIT, odb_path = GIT_BUF_INIT; int error; size_t j; GIT_UNUSED(cbs); /* 'push->remote->url' may be a url or path; convert to a path */ if ((error = git_path_from_url_or_path(&buf, push->remote->url)) < 0) { git_buf_dispose(&buf); return error; } path = git_buf_cstr(&buf); error = git_repository_open(&remote_repo, path); git_buf_dispose(&buf); if (error < 0) return error; /* We don't currently support pushing locally to non-bare repos. Proper non-bare repo push support would require checking configs to see if we should override the default 'don't let this happen' behavior. Note that this is only an issue when pushing to the current branch, but we forbid all pushes just in case */ if (!remote_repo->is_bare) { error = GIT_EBAREREPO; git_error_set(GIT_ERROR_INVALID, "local push doesn't (yet) support pushing to non-bare repos."); goto on_error; } if ((error = git_repository_item_path(&odb_path, remote_repo, GIT_REPOSITORY_ITEM_OBJECTS)) < 0 || (error = git_buf_joinpath(&odb_path, odb_path.ptr, "pack")) < 0) goto on_error; error = git_packbuilder_write(push->pb, odb_path.ptr, 0, transfer_to_push_transfer, (void *) cbs); git_buf_dispose(&odb_path); if (error < 0) goto on_error; push->unpack_ok = 1; git_vector_foreach(&push->specs, j, spec) { push_status *status; const git_error *last; char *ref = spec->refspec.dst; status = git__calloc(1, sizeof(push_status)); if (!status) goto on_error; status->ref = git__strdup(ref); if (!status->ref) { git_push_status_free(status); goto on_error; } error = local_push_update_remote_ref(remote_repo, spec->refspec.src, spec->refspec.dst, &spec->loid, &spec->roid); switch (error) { case GIT_OK: break; case GIT_EINVALIDSPEC: status->msg = git__strdup("funny refname"); break; case GIT_ENOTFOUND: status->msg = git__strdup("Remote branch not found to delete"); break; default: last = git_error_last(); if (last && last->message) status->msg = git__strdup(last->message); else status->msg = git__strdup("Unspecified error encountered"); break; } /* failed to allocate memory for a status message */ if (error < 0 && !status->msg) { git_push_status_free(status); goto on_error; } /* failed to insert the ref update status */ if ((error = git_vector_insert(&push->status, status)) < 0) { git_push_status_free(status); goto on_error; } } if (push->specs.length) { int flags = t->flags; url = git__strdup(t->url); if (!url || t->parent.close(&t->parent) < 0 || t->parent.connect(&t->parent, url, NULL, NULL, NULL, GIT_DIRECTION_PUSH, flags)) goto on_error; } error = 0; on_error: git_repository_free(remote_repo); git__free(url); return error; } typedef struct foreach_data { git_indexer_progress *stats; git_indexer_progress_cb progress_cb; void *progress_payload; git_odb_writepack *writepack; } foreach_data; static int foreach_cb(void *buf, size_t len, void *payload) { foreach_data *data = (foreach_data*)payload; data->stats->received_bytes += len; return data->writepack->append(data->writepack, buf, len, data->stats); } static const char *counting_objects_fmt = "Counting objects %d\r"; static const char *compressing_objects_fmt = "Compressing objects: %.0f%% (%d/%d)"; static int local_counting(int stage, unsigned int current, unsigned int total, void *payload) { git_buf progress_info = GIT_BUF_INIT; transport_local *t = payload; int error; if (!t->progress_cb) return 0; if (stage == GIT_PACKBUILDER_ADDING_OBJECTS) { git_buf_printf(&progress_info, counting_objects_fmt, current); } else if (stage == GIT_PACKBUILDER_DELTAFICATION) { float perc = (((float) current) / total) * 100; git_buf_printf(&progress_info, compressing_objects_fmt, perc, current, total); if (current == total) git_buf_printf(&progress_info, ", done\n"); else git_buf_putc(&progress_info, '\r'); } if (git_buf_oom(&progress_info)) return -1; error = t->progress_cb(git_buf_cstr(&progress_info), (int)git_buf_len(&progress_info), t->message_cb_payload); git_buf_dispose(&progress_info); return error; } static int foreach_reference_cb(git_reference *reference, void *payload) { git_revwalk *walk = (git_revwalk *)payload; int error; if (git_reference_type(reference) != GIT_REFERENCE_DIRECT) { git_reference_free(reference); return 0; } error = git_revwalk_hide(walk, git_reference_target(reference)); /* The reference is in the local repository, so the target may not * exist on the remote. It also may not be a commit. */ if (error == GIT_ENOTFOUND || error == GIT_ERROR_INVALID) { git_error_clear(); error = 0; } git_reference_free(reference); return error; } static int local_download_pack( git_transport *transport, git_repository *repo, git_indexer_progress *stats, git_indexer_progress_cb progress_cb, void *progress_payload) { transport_local *t = (transport_local*)transport; git_revwalk *walk = NULL; git_remote_head *rhead; unsigned int i; int error = -1; git_packbuilder *pack = NULL; git_odb_writepack *writepack = NULL; git_odb *odb = NULL; git_buf progress_info = GIT_BUF_INIT; if ((error = git_revwalk_new(&walk, t->repo)) < 0) goto cleanup; git_revwalk_sorting(walk, GIT_SORT_TIME); if ((error = git_packbuilder_new(&pack, t->repo)) < 0) goto cleanup; git_packbuilder_set_callbacks(pack, local_counting, t); stats->total_objects = 0; stats->indexed_objects = 0; stats->received_objects = 0; stats->received_bytes = 0; git_vector_foreach(&t->refs, i, rhead) { git_object *obj; if ((error = git_object_lookup(&obj, t->repo, &rhead->oid, GIT_OBJECT_ANY)) < 0) goto cleanup; if (git_object_type(obj) == GIT_OBJECT_COMMIT) { /* Revwalker includes only wanted commits */ error = git_revwalk_push(walk, &rhead->oid); } else { /* Tag or some other wanted object. Add it on its own */ error = git_packbuilder_insert_recur(pack, &rhead->oid, rhead->name); } git_object_free(obj); if (error < 0) goto cleanup; } if ((error = git_reference_foreach(repo, foreach_reference_cb, walk))) goto cleanup; if ((error = git_packbuilder_insert_walk(pack, walk))) goto cleanup; if ((error = git_buf_printf(&progress_info, counting_objects_fmt, git_packbuilder_object_count(pack))) < 0) goto cleanup; if (t->progress_cb && (error = t->progress_cb(git_buf_cstr(&progress_info), (int)git_buf_len(&progress_info), t->message_cb_payload)) < 0) goto cleanup; /* Walk the objects, building a packfile */ if ((error = git_repository_odb__weakptr(&odb, repo)) < 0) goto cleanup; /* One last one with the newline */ git_buf_clear(&progress_info); git_buf_printf(&progress_info, counting_objects_fmt, git_packbuilder_object_count(pack)); if ((error = git_buf_putc(&progress_info, '\n')) < 0) goto cleanup; if (t->progress_cb && (error = t->progress_cb(git_buf_cstr(&progress_info), (int)git_buf_len(&progress_info), t->message_cb_payload)) < 0) goto cleanup; if ((error = git_odb_write_pack(&writepack, odb, progress_cb, progress_payload)) != 0) goto cleanup; /* Write the data to the ODB */ { foreach_data data = {0}; data.stats = stats; data.progress_cb = progress_cb; data.progress_payload = progress_payload; data.writepack = writepack; /* autodetect */ git_packbuilder_set_threads(pack, 0); if ((error = git_packbuilder_foreach(pack, foreach_cb, &data)) != 0) goto cleanup; } error = writepack->commit(writepack, stats); cleanup: if (writepack) writepack->free(writepack); git_buf_dispose(&progress_info); git_packbuilder_free(pack); git_revwalk_free(walk); return error; } static int local_set_callbacks( git_transport *transport, git_transport_message_cb progress_cb, git_transport_message_cb error_cb, git_transport_certificate_check_cb certificate_check_cb, void *message_cb_payload) { transport_local *t = (transport_local *)transport; GIT_UNUSED(certificate_check_cb); t->progress_cb = progress_cb; t->error_cb = error_cb; t->message_cb_payload = message_cb_payload; return 0; } static int local_is_connected(git_transport *transport) { transport_local *t = (transport_local *)transport; return t->connected; } static int local_read_flags(git_transport *transport, int *flags) { transport_local *t = (transport_local *)transport; *flags = t->flags; return 0; } static void local_cancel(git_transport *transport) { transport_local *t = (transport_local *)transport; git_atomic32_set(&t->cancelled, 1); } static int local_close(git_transport *transport) { transport_local *t = (transport_local *)transport; t->connected = 0; if (t->repo) { git_repository_free(t->repo); t->repo = NULL; } if (t->url) { git__free(t->url); t->url = NULL; } return 0; } static void local_free(git_transport *transport) { transport_local *t = (transport_local *)transport; free_heads(&t->refs); /* Close the transport, if it's still open. */ local_close(transport); /* Free the transport */ git__free(t); } /************** * Public API * **************/ int git_transport_local(git_transport **out, git_remote *owner, void *param) { int error; transport_local *t; GIT_UNUSED(param); t = git__calloc(1, sizeof(transport_local)); GIT_ERROR_CHECK_ALLOC(t); t->parent.version = GIT_TRANSPORT_VERSION; t->parent.set_callbacks = local_set_callbacks; t->parent.connect = local_connect; t->parent.negotiate_fetch = local_negotiate_fetch; t->parent.download_pack = local_download_pack; t->parent.push = local_push; t->parent.close = local_close; t->parent.free = local_free; t->parent.ls = local_ls; t->parent.is_connected = local_is_connected; t->parent.read_flags = local_read_flags; t->parent.cancel = local_cancel; if ((error = git_vector_init(&t->refs, 0, NULL)) < 0) { git__free(t); return error; } t->owner = owner; *out = (git_transport *) t; return 0; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/transports/auth.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_transports_auth_h__ #define INCLUDE_transports_auth_h__ #include "common.h" #include "git2.h" #include "netops.h" typedef enum { GIT_HTTP_AUTH_BASIC = 1, GIT_HTTP_AUTH_NEGOTIATE = 2, GIT_HTTP_AUTH_NTLM = 4, } git_http_auth_t; typedef struct git_http_auth_context git_http_auth_context; struct git_http_auth_context { /** Type of scheme */ git_http_auth_t type; /** Supported credentials */ git_credential_t credtypes; /** Connection affinity or request affinity */ unsigned connection_affinity : 1; /** Sets the challenge on the authentication context */ int (*set_challenge)(git_http_auth_context *ctx, const char *challenge); /** Gets the next authentication token from the context */ int (*next_token)(git_buf *out, git_http_auth_context *ctx, git_credential *cred); /** Examines if all tokens have been presented. */ int (*is_complete)(git_http_auth_context *ctx); /** Frees the authentication context */ void (*free)(git_http_auth_context *ctx); }; typedef struct { /** Type of scheme */ git_http_auth_t type; /** Name of the scheme (as used in the Authorization header) */ const char *name; /** Credential types this scheme supports */ git_credential_t credtypes; /** Function to initialize an authentication context */ int (*init_context)( git_http_auth_context **out, const git_net_url *url); } git_http_auth_scheme; int git_http_auth_dummy( git_http_auth_context **out, const git_net_url *url); int git_http_auth_basic( git_http_auth_context **out, const git_net_url *url); #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/transports/auth_negotiate.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_transports_auth_negotiate_h__ #define INCLUDE_transports_auth_negotiate_h__ #include "common.h" #include "git2.h" #include "auth.h" #if defined(GIT_GSSAPI) || defined(GIT_GSSFRAMEWORK) extern int git_http_auth_negotiate( git_http_auth_context **out, const git_net_url *url); #else #define git_http_auth_negotiate git_http_auth_dummy #endif /* GIT_GSSAPI */ #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/transports/credential_helpers.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "common.h" #include "git2/credential_helpers.h" int git_credential_userpass( git_credential **cred, const char *url, const char *user_from_url, unsigned int allowed_types, void *payload) { git_credential_userpass_payload *userpass = (git_credential_userpass_payload*)payload; const char *effective_username = NULL; GIT_UNUSED(url); if (!userpass || !userpass->password) return -1; /* Username resolution: a username can be passed with the URL, the * credentials payload, or both. Here's what we do. Note that if we get * this far, we know that any password the url may contain has already * failed at least once, so we ignore it. * * | Payload | URL | Used | * +-------------+----------+-----------+ * | yes | no | payload | * | yes | yes | payload | * | no | yes | url | * | no | no | FAIL | */ if (userpass->username) effective_username = userpass->username; else if (user_from_url) effective_username = user_from_url; else return -1; if (GIT_CREDENTIAL_USERNAME & allowed_types) return git_credential_username_new(cred, effective_username); if ((GIT_CREDENTIAL_USERPASS_PLAINTEXT & allowed_types) == 0 || git_credential_userpass_plaintext_new(cred, effective_username, userpass->password) < 0) return -1; return 0; } /* Deprecated credential functions */ #ifndef GIT_DEPRECATE_HARD int git_cred_userpass( git_credential **out, const char *url, const char *user_from_url, unsigned int allowed_types, void *payload) { return git_credential_userpass(out, url, user_from_url, allowed_types, payload); } #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/transports/smart_pkt.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "common.h" #include "git2/types.h" #include "git2/errors.h" #include "git2/refs.h" #include "git2/revwalk.h" #include "smart.h" #include "util.h" #include "netops.h" #include "posix.h" #include "buffer.h" #include <ctype.h> #define PKT_LEN_SIZE 4 static const char pkt_done_str[] = "0009done\n"; static const char pkt_flush_str[] = "0000"; static const char pkt_have_prefix[] = "0032have "; static const char pkt_want_prefix[] = "0032want "; static int flush_pkt(git_pkt **out) { git_pkt *pkt; pkt = git__malloc(sizeof(git_pkt)); GIT_ERROR_CHECK_ALLOC(pkt); pkt->type = GIT_PKT_FLUSH; *out = pkt; return 0; } /* the rest of the line will be useful for multi_ack and multi_ack_detailed */ static int ack_pkt(git_pkt **out, const char *line, size_t len) { git_pkt_ack *pkt; pkt = git__calloc(1, sizeof(git_pkt_ack)); GIT_ERROR_CHECK_ALLOC(pkt); pkt->type = GIT_PKT_ACK; if (git__prefixncmp(line, len, "ACK ")) goto out_err; line += 4; len -= 4; if (len < GIT_OID_HEXSZ || git_oid_fromstr(&pkt->oid, line) < 0) goto out_err; line += GIT_OID_HEXSZ; len -= GIT_OID_HEXSZ; if (len && line[0] == ' ') { line++; len--; if (!git__prefixncmp(line, len, "continue")) pkt->status = GIT_ACK_CONTINUE; else if (!git__prefixncmp(line, len, "common")) pkt->status = GIT_ACK_COMMON; else if (!git__prefixncmp(line, len, "ready")) pkt->status = GIT_ACK_READY; else goto out_err; } *out = (git_pkt *) pkt; return 0; out_err: git_error_set(GIT_ERROR_NET, "error parsing ACK pkt-line"); git__free(pkt); return -1; } static int nak_pkt(git_pkt **out) { git_pkt *pkt; pkt = git__malloc(sizeof(git_pkt)); GIT_ERROR_CHECK_ALLOC(pkt); pkt->type = GIT_PKT_NAK; *out = pkt; return 0; } static int comment_pkt(git_pkt **out, const char *line, size_t len) { git_pkt_comment *pkt; size_t alloclen; GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_pkt_comment), len); GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, alloclen, 1); pkt = git__malloc(alloclen); GIT_ERROR_CHECK_ALLOC(pkt); pkt->type = GIT_PKT_COMMENT; memcpy(pkt->comment, line, len); pkt->comment[len] = '\0'; *out = (git_pkt *) pkt; return 0; } static int err_pkt(git_pkt **out, const char *line, size_t len) { git_pkt_err *pkt = NULL; size_t alloclen; /* Remove "ERR " from the line */ if (git__prefixncmp(line, len, "ERR ")) goto out_err; line += 4; len -= 4; GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_pkt_progress), len); GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, alloclen, 1); pkt = git__malloc(alloclen); GIT_ERROR_CHECK_ALLOC(pkt); pkt->type = GIT_PKT_ERR; pkt->len = len; memcpy(pkt->error, line, len); pkt->error[len] = '\0'; *out = (git_pkt *) pkt; return 0; out_err: git_error_set(GIT_ERROR_NET, "error parsing ERR pkt-line"); git__free(pkt); return -1; } static int data_pkt(git_pkt **out, const char *line, size_t len) { git_pkt_data *pkt; size_t alloclen; line++; len--; GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_pkt_progress), len); pkt = git__malloc(alloclen); GIT_ERROR_CHECK_ALLOC(pkt); pkt->type = GIT_PKT_DATA; pkt->len = len; memcpy(pkt->data, line, len); *out = (git_pkt *) pkt; return 0; } static int sideband_progress_pkt(git_pkt **out, const char *line, size_t len) { git_pkt_progress *pkt; size_t alloclen; line++; len--; GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_pkt_progress), len); pkt = git__malloc(alloclen); GIT_ERROR_CHECK_ALLOC(pkt); pkt->type = GIT_PKT_PROGRESS; pkt->len = len; memcpy(pkt->data, line, len); *out = (git_pkt *) pkt; return 0; } static int sideband_error_pkt(git_pkt **out, const char *line, size_t len) { git_pkt_err *pkt; size_t alloc_len; line++; len--; GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, sizeof(git_pkt_err), len); GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, alloc_len, 1); pkt = git__malloc(alloc_len); GIT_ERROR_CHECK_ALLOC(pkt); pkt->type = GIT_PKT_ERR; pkt->len = (int)len; memcpy(pkt->error, line, len); pkt->error[len] = '\0'; *out = (git_pkt *)pkt; return 0; } /* * Parse an other-ref line. */ static int ref_pkt(git_pkt **out, const char *line, size_t len) { git_pkt_ref *pkt; size_t alloclen; pkt = git__calloc(1, sizeof(git_pkt_ref)); GIT_ERROR_CHECK_ALLOC(pkt); pkt->type = GIT_PKT_REF; if (len < GIT_OID_HEXSZ || git_oid_fromstr(&pkt->head.oid, line) < 0) goto out_err; line += GIT_OID_HEXSZ; len -= GIT_OID_HEXSZ; if (git__prefixncmp(line, len, " ")) goto out_err; line++; len--; if (!len) goto out_err; if (line[len - 1] == '\n') --len; GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, len, 1); pkt->head.name = git__malloc(alloclen); GIT_ERROR_CHECK_ALLOC(pkt->head.name); memcpy(pkt->head.name, line, len); pkt->head.name[len] = '\0'; if (strlen(pkt->head.name) < len) pkt->capabilities = strchr(pkt->head.name, '\0') + 1; *out = (git_pkt *)pkt; return 0; out_err: git_error_set(GIT_ERROR_NET, "error parsing REF pkt-line"); if (pkt) git__free(pkt->head.name); git__free(pkt); return -1; } static int ok_pkt(git_pkt **out, const char *line, size_t len) { git_pkt_ok *pkt; size_t alloc_len; pkt = git__malloc(sizeof(*pkt)); GIT_ERROR_CHECK_ALLOC(pkt); pkt->type = GIT_PKT_OK; if (git__prefixncmp(line, len, "ok ")) goto out_err; line += 3; len -= 3; if (len && line[len - 1] == '\n') --len; GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, len, 1); pkt->ref = git__malloc(alloc_len); GIT_ERROR_CHECK_ALLOC(pkt->ref); memcpy(pkt->ref, line, len); pkt->ref[len] = '\0'; *out = (git_pkt *)pkt; return 0; out_err: git_error_set(GIT_ERROR_NET, "error parsing OK pkt-line"); git__free(pkt); return -1; } static int ng_pkt(git_pkt **out, const char *line, size_t len) { git_pkt_ng *pkt; const char *ptr, *eol; size_t alloclen; pkt = git__malloc(sizeof(*pkt)); GIT_ERROR_CHECK_ALLOC(pkt); pkt->ref = NULL; pkt->type = GIT_PKT_NG; eol = line + len; if (git__prefixncmp(line, len, "ng ")) goto out_err; line += 3; if (!(ptr = memchr(line, ' ', eol - line))) goto out_err; len = ptr - line; GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, len, 1); pkt->ref = git__malloc(alloclen); GIT_ERROR_CHECK_ALLOC(pkt->ref); memcpy(pkt->ref, line, len); pkt->ref[len] = '\0'; line = ptr + 1; if (line >= eol) goto out_err; if (!(ptr = memchr(line, '\n', eol - line))) goto out_err; len = ptr - line; GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, len, 1); pkt->msg = git__malloc(alloclen); GIT_ERROR_CHECK_ALLOC(pkt->msg); memcpy(pkt->msg, line, len); pkt->msg[len] = '\0'; *out = (git_pkt *)pkt; return 0; out_err: git_error_set(GIT_ERROR_NET, "invalid packet line"); git__free(pkt->ref); git__free(pkt); return -1; } static int unpack_pkt(git_pkt **out, const char *line, size_t len) { git_pkt_unpack *pkt; pkt = git__malloc(sizeof(*pkt)); GIT_ERROR_CHECK_ALLOC(pkt); pkt->type = GIT_PKT_UNPACK; if (!git__prefixncmp(line, len, "unpack ok")) pkt->unpack_ok = 1; else pkt->unpack_ok = 0; *out = (git_pkt *)pkt; return 0; } static int parse_len(size_t *out, const char *line, size_t linelen) { char num[PKT_LEN_SIZE + 1]; int i, k, error; int32_t len; const char *num_end; /* Not even enough for the length */ if (linelen < PKT_LEN_SIZE) return GIT_EBUFS; memcpy(num, line, PKT_LEN_SIZE); num[PKT_LEN_SIZE] = '\0'; for (i = 0; i < PKT_LEN_SIZE; ++i) { if (!isxdigit(num[i])) { /* Make sure there are no special characters before passing to error message */ for (k = 0; k < PKT_LEN_SIZE; ++k) { if(!isprint(num[k])) { num[k] = '.'; } } git_error_set(GIT_ERROR_NET, "invalid hex digit in length: '%s'", num); return -1; } } if ((error = git__strntol32(&len, num, PKT_LEN_SIZE, &num_end, 16)) < 0) return error; if (len < 0) return -1; *out = (size_t) len; return 0; } /* * As per the documentation, the syntax is: * * pkt-line = data-pkt / flush-pkt * data-pkt = pkt-len pkt-payload * pkt-len = 4*(HEXDIG) * pkt-payload = (pkt-len -4)*(OCTET) * flush-pkt = "0000" * * Which means that the first four bytes are the length of the line, * in ASCII hexadecimal (including itself) */ int git_pkt_parse_line( git_pkt **pkt, const char **endptr, const char *line, size_t linelen) { int error; size_t len; if ((error = parse_len(&len, line, linelen)) < 0) { /* * If we fail to parse the length, it might be * because the server is trying to send us the * packfile already or because we do not yet have * enough data. */ if (error == GIT_EBUFS) ; else if (!git__prefixncmp(line, linelen, "PACK")) git_error_set(GIT_ERROR_NET, "unexpected pack file"); else git_error_set(GIT_ERROR_NET, "bad packet length"); return error; } /* * Make sure there is enough in the buffer to satisfy * this line. */ if (linelen < len) return GIT_EBUFS; /* * The length has to be exactly 0 in case of a flush * packet or greater than PKT_LEN_SIZE, as the decoded * length includes its own encoded length of four bytes. */ if (len != 0 && len < PKT_LEN_SIZE) return GIT_ERROR; line += PKT_LEN_SIZE; /* * The Git protocol does not specify empty lines as part * of the protocol. Not knowing what to do with an empty * line, we should return an error upon hitting one. */ if (len == PKT_LEN_SIZE) { git_error_set_str(GIT_ERROR_NET, "Invalid empty packet"); return GIT_ERROR; } if (len == 0) { /* Flush pkt */ *endptr = line; return flush_pkt(pkt); } len -= PKT_LEN_SIZE; /* the encoded length includes its own size */ if (*line == GIT_SIDE_BAND_DATA) error = data_pkt(pkt, line, len); else if (*line == GIT_SIDE_BAND_PROGRESS) error = sideband_progress_pkt(pkt, line, len); else if (*line == GIT_SIDE_BAND_ERROR) error = sideband_error_pkt(pkt, line, len); else if (!git__prefixncmp(line, len, "ACK")) error = ack_pkt(pkt, line, len); else if (!git__prefixncmp(line, len, "NAK")) error = nak_pkt(pkt); else if (!git__prefixncmp(line, len, "ERR")) error = err_pkt(pkt, line, len); else if (*line == '#') error = comment_pkt(pkt, line, len); else if (!git__prefixncmp(line, len, "ok")) error = ok_pkt(pkt, line, len); else if (!git__prefixncmp(line, len, "ng")) error = ng_pkt(pkt, line, len); else if (!git__prefixncmp(line, len, "unpack")) error = unpack_pkt(pkt, line, len); else error = ref_pkt(pkt, line, len); *endptr = line + len; return error; } void git_pkt_free(git_pkt *pkt) { if (pkt == NULL) { return; } if (pkt->type == GIT_PKT_REF) { git_pkt_ref *p = (git_pkt_ref *) pkt; git__free(p->head.name); git__free(p->head.symref_target); } if (pkt->type == GIT_PKT_OK) { git_pkt_ok *p = (git_pkt_ok *) pkt; git__free(p->ref); } if (pkt->type == GIT_PKT_NG) { git_pkt_ng *p = (git_pkt_ng *) pkt; git__free(p->ref); git__free(p->msg); } git__free(pkt); } int git_pkt_buffer_flush(git_buf *buf) { return git_buf_put(buf, pkt_flush_str, strlen(pkt_flush_str)); } static int buffer_want_with_caps(const git_remote_head *head, transport_smart_caps *caps, git_buf *buf) { git_buf str = GIT_BUF_INIT; char oid[GIT_OID_HEXSZ +1] = {0}; size_t len; /* Prefer multi_ack_detailed */ if (caps->multi_ack_detailed) git_buf_puts(&str, GIT_CAP_MULTI_ACK_DETAILED " "); else if (caps->multi_ack) git_buf_puts(&str, GIT_CAP_MULTI_ACK " "); /* Prefer side-band-64k if the server supports both */ if (caps->side_band_64k) git_buf_printf(&str, "%s ", GIT_CAP_SIDE_BAND_64K); else if (caps->side_band) git_buf_printf(&str, "%s ", GIT_CAP_SIDE_BAND); if (caps->include_tag) git_buf_puts(&str, GIT_CAP_INCLUDE_TAG " "); if (caps->thin_pack) git_buf_puts(&str, GIT_CAP_THIN_PACK " "); if (caps->ofs_delta) git_buf_puts(&str, GIT_CAP_OFS_DELTA " "); if (git_buf_oom(&str)) return -1; len = strlen("XXXXwant ") + GIT_OID_HEXSZ + 1 /* NUL */ + git_buf_len(&str) + 1 /* LF */; if (len > 0xffff) { git_error_set(GIT_ERROR_NET, "tried to produce packet with invalid length %" PRIuZ, len); return -1; } git_buf_grow_by(buf, len); git_oid_fmt(oid, &head->oid); git_buf_printf(buf, "%04xwant %s %s\n", (unsigned int)len, oid, git_buf_cstr(&str)); git_buf_dispose(&str); GIT_ERROR_CHECK_ALLOC_BUF(buf); return 0; } /* * All "want" packets have the same length and format, so what we do * is overwrite the OID each time. */ int git_pkt_buffer_wants( const git_remote_head * const *refs, size_t count, transport_smart_caps *caps, git_buf *buf) { size_t i = 0; const git_remote_head *head; if (caps->common) { for (; i < count; ++i) { head = refs[i]; if (!head->local) break; } if (buffer_want_with_caps(refs[i], caps, buf) < 0) return -1; i++; } for (; i < count; ++i) { char oid[GIT_OID_HEXSZ]; head = refs[i]; if (head->local) continue; git_oid_fmt(oid, &head->oid); git_buf_put(buf, pkt_want_prefix, strlen(pkt_want_prefix)); git_buf_put(buf, oid, GIT_OID_HEXSZ); git_buf_putc(buf, '\n'); if (git_buf_oom(buf)) return -1; } return git_pkt_buffer_flush(buf); } int git_pkt_buffer_have(git_oid *oid, git_buf *buf) { char oidhex[GIT_OID_HEXSZ + 1]; memset(oidhex, 0x0, sizeof(oidhex)); git_oid_fmt(oidhex, oid); return git_buf_printf(buf, "%s%s\n", pkt_have_prefix, oidhex); } int git_pkt_buffer_done(git_buf *buf) { return git_buf_puts(buf, pkt_done_str); }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/transports/auth_ntlm.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_transports_auth_ntlm_h__ #define INCLUDE_transports_auth_ntlm_h__ #include "git2.h" #include "auth.h" /* NTLM requires a full request/challenge/response */ #define GIT_AUTH_STEPS_NTLM 2 #ifdef GIT_NTLM #if defined(GIT_OPENSSL) # define CRYPT_OPENSSL #elif defined(GIT_MBEDTLS) # define CRYPT_MBEDTLS #elif defined(GIT_SECURE_TRANSPORT) # define CRYPT_COMMONCRYPTO #endif extern int git_http_auth_ntlm( git_http_auth_context **out, const git_net_url *url); #else #define git_http_auth_ntlm git_http_auth_dummy #endif /* GIT_NTLM */ #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/transports/git.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "common.h" #include "git2.h" #include "buffer.h" #include "netops.h" #include "git2/sys/transport.h" #include "stream.h" #include "streams/socket.h" #define OWNING_SUBTRANSPORT(s) ((git_subtransport *)(s)->parent.subtransport) static const char prefix_git[] = "git://"; static const char cmd_uploadpack[] = "git-upload-pack"; static const char cmd_receivepack[] = "git-receive-pack"; typedef struct { git_smart_subtransport_stream parent; git_stream *io; const char *cmd; char *url; unsigned sent_command : 1; } git_proto_stream; typedef struct { git_smart_subtransport parent; git_transport *owner; git_proto_stream *current_stream; } git_subtransport; /* * Create a git protocol request. * * For example: 0035git-upload-pack /libgit2/libgit2\0host=github.com\0 */ static int gen_proto(git_buf *request, const char *cmd, const char *url) { char *delim, *repo; char host[] = "host="; size_t len; delim = strchr(url, '/'); if (delim == NULL) { git_error_set(GIT_ERROR_NET, "malformed URL"); return -1; } repo = delim; if (repo[1] == '~') ++repo; delim = strchr(url, ':'); if (delim == NULL) delim = strchr(url, '/'); len = 4 + strlen(cmd) + 1 + strlen(repo) + 1 + strlen(host) + (delim - url) + 1; git_buf_grow(request, len); git_buf_printf(request, "%04x%s %s%c%s", (unsigned int)(len & 0x0FFFF), cmd, repo, 0, host); git_buf_put(request, url, delim - url); git_buf_putc(request, '\0'); if (git_buf_oom(request)) return -1; return 0; } static int send_command(git_proto_stream *s) { git_buf request = GIT_BUF_INIT; int error; if ((error = gen_proto(&request, s->cmd, s->url)) < 0) goto cleanup; if ((error = git_stream__write_full(s->io, request.ptr, request.size, 0)) < 0) goto cleanup; s->sent_command = 1; cleanup: git_buf_dispose(&request); return error; } static int git_proto_stream_read( git_smart_subtransport_stream *stream, char *buffer, size_t buf_size, size_t *bytes_read) { int error; git_proto_stream *s = (git_proto_stream *)stream; gitno_buffer buf; *bytes_read = 0; if (!s->sent_command && (error = send_command(s)) < 0) return error; gitno_buffer_setup_fromstream(s->io, &buf, buffer, buf_size); if ((error = gitno_recv(&buf)) < 0) return error; *bytes_read = buf.offset; return 0; } static int git_proto_stream_write( git_smart_subtransport_stream *stream, const char *buffer, size_t len) { git_proto_stream *s = (git_proto_stream *)stream; int error; if (!s->sent_command && (error = send_command(s)) < 0) return error; return git_stream__write_full(s->io, buffer, len, 0); } static void git_proto_stream_free(git_smart_subtransport_stream *stream) { git_proto_stream *s; git_subtransport *t; if (!stream) return; s = (git_proto_stream *)stream; t = OWNING_SUBTRANSPORT(s); t->current_stream = NULL; git_stream_close(s->io); git_stream_free(s->io); git__free(s->url); git__free(s); } static int git_proto_stream_alloc( git_subtransport *t, const char *url, const char *cmd, const char *host, const char *port, git_smart_subtransport_stream **stream) { git_proto_stream *s; if (!stream) return -1; s = git__calloc(1, sizeof(git_proto_stream)); GIT_ERROR_CHECK_ALLOC(s); s->parent.subtransport = &t->parent; s->parent.read = git_proto_stream_read; s->parent.write = git_proto_stream_write; s->parent.free = git_proto_stream_free; s->cmd = cmd; s->url = git__strdup(url); if (!s->url) { git__free(s); return -1; } if ((git_socket_stream_new(&s->io, host, port)) < 0) return -1; GIT_ERROR_CHECK_VERSION(s->io, GIT_STREAM_VERSION, "git_stream"); *stream = &s->parent; return 0; } static int _git_uploadpack_ls( git_subtransport *t, const char *url, git_smart_subtransport_stream **stream) { git_net_url urldata = GIT_NET_URL_INIT; const char *stream_url = url; const char *host, *port; git_proto_stream *s; int error; *stream = NULL; if (!git__prefixcmp(url, prefix_git)) stream_url += strlen(prefix_git); if ((error = git_net_url_parse(&urldata, url)) < 0) return error; host = urldata.host; port = urldata.port ? urldata.port : GIT_DEFAULT_PORT; error = git_proto_stream_alloc(t, stream_url, cmd_uploadpack, host, port, stream); git_net_url_dispose(&urldata); if (error < 0) { git_proto_stream_free(*stream); return error; } s = (git_proto_stream *) *stream; if ((error = git_stream_connect(s->io)) < 0) { git_proto_stream_free(*stream); return error; } t->current_stream = s; return 0; } static int _git_uploadpack( git_subtransport *t, const char *url, git_smart_subtransport_stream **stream) { GIT_UNUSED(url); if (t->current_stream) { *stream = &t->current_stream->parent; return 0; } git_error_set(GIT_ERROR_NET, "must call UPLOADPACK_LS before UPLOADPACK"); return -1; } static int _git_receivepack_ls( git_subtransport *t, const char *url, git_smart_subtransport_stream **stream) { git_net_url urldata = GIT_NET_URL_INIT; const char *stream_url = url; git_proto_stream *s; int error; *stream = NULL; if (!git__prefixcmp(url, prefix_git)) stream_url += strlen(prefix_git); if ((error = git_net_url_parse(&urldata, url)) < 0) return error; error = git_proto_stream_alloc(t, stream_url, cmd_receivepack, urldata.host, urldata.port, stream); git_net_url_dispose(&urldata); if (error < 0) { git_proto_stream_free(*stream); return error; } s = (git_proto_stream *) *stream; if ((error = git_stream_connect(s->io)) < 0) return error; t->current_stream = s; return 0; } static int _git_receivepack( git_subtransport *t, const char *url, git_smart_subtransport_stream **stream) { GIT_UNUSED(url); if (t->current_stream) { *stream = &t->current_stream->parent; return 0; } git_error_set(GIT_ERROR_NET, "must call RECEIVEPACK_LS before RECEIVEPACK"); return -1; } static int _git_action( git_smart_subtransport_stream **stream, git_smart_subtransport *subtransport, const char *url, git_smart_service_t action) { git_subtransport *t = (git_subtransport *) subtransport; switch (action) { case GIT_SERVICE_UPLOADPACK_LS: return _git_uploadpack_ls(t, url, stream); case GIT_SERVICE_UPLOADPACK: return _git_uploadpack(t, url, stream); case GIT_SERVICE_RECEIVEPACK_LS: return _git_receivepack_ls(t, url, stream); case GIT_SERVICE_RECEIVEPACK: return _git_receivepack(t, url, stream); } *stream = NULL; return -1; } static int _git_close(git_smart_subtransport *subtransport) { git_subtransport *t = (git_subtransport *) subtransport; GIT_ASSERT(!t->current_stream); GIT_UNUSED(t); return 0; } static void _git_free(git_smart_subtransport *subtransport) { git_subtransport *t = (git_subtransport *) subtransport; git__free(t); } int git_smart_subtransport_git(git_smart_subtransport **out, git_transport *owner, void *param) { git_subtransport *t; GIT_UNUSED(param); if (!out) return -1; t = git__calloc(1, sizeof(git_subtransport)); GIT_ERROR_CHECK_ALLOC(t); t->owner = owner; t->parent.action = _git_action; t->parent.close = _git_close; t->parent.free = _git_free; *out = (git_smart_subtransport *) t; return 0; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/transports/auth.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "auth.h" #include "git2.h" #include "buffer.h" #include "git2/sys/credential.h" static int basic_next_token( git_buf *out, git_http_auth_context *ctx, git_credential *c) { git_credential_userpass_plaintext *cred; git_buf raw = GIT_BUF_INIT; int error = GIT_EAUTH; GIT_UNUSED(ctx); if (c->credtype != GIT_CREDENTIAL_USERPASS_PLAINTEXT) { git_error_set(GIT_ERROR_INVALID, "invalid credential type for basic auth"); goto on_error; } cred = (git_credential_userpass_plaintext *)c; git_buf_printf(&raw, "%s:%s", cred->username, cred->password); if (git_buf_oom(&raw) || git_buf_puts(out, "Basic ") < 0 || git_buf_encode_base64(out, git_buf_cstr(&raw), raw.size) < 0) goto on_error; error = 0; on_error: if (raw.size) git__memzero(raw.ptr, raw.size); git_buf_dispose(&raw); return error; } static git_http_auth_context basic_context = { GIT_HTTP_AUTH_BASIC, GIT_CREDENTIAL_USERPASS_PLAINTEXT, 0, NULL, basic_next_token, NULL, NULL }; int git_http_auth_basic( git_http_auth_context **out, const git_net_url *url) { GIT_UNUSED(url); *out = &basic_context; return 0; } int git_http_auth_dummy( git_http_auth_context **out, const git_net_url *url) { GIT_UNUSED(url); *out = NULL; return GIT_PASSTHROUGH; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/transports/ssh.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_transports_ssh_h__ #define INCLUDE_transports_ssh_h__ #include "common.h" int git_transport_ssh_global_init(void); #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/transports/http.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "common.h" #ifndef GIT_WINHTTP #include "git2.h" #include "http_parser.h" #include "buffer.h" #include "net.h" #include "netops.h" #include "remote.h" #include "git2/sys/credential.h" #include "smart.h" #include "auth.h" #include "http.h" #include "auth_negotiate.h" #include "auth_ntlm.h" #include "trace.h" #include "streams/tls.h" #include "streams/socket.h" #include "httpclient.h" bool git_http__expect_continue = false; typedef enum { HTTP_STATE_NONE = 0, HTTP_STATE_SENDING_REQUEST, HTTP_STATE_RECEIVING_RESPONSE, HTTP_STATE_DONE } http_state; typedef struct { git_http_method method; const char *url; const char *request_type; const char *response_type; unsigned chunked : 1; } http_service; typedef struct { git_smart_subtransport_stream parent; const http_service *service; http_state state; unsigned replay_count; } http_stream; typedef struct { git_net_url url; git_credential *cred; unsigned auth_schemetypes; unsigned url_cred_presented : 1; } http_server; typedef struct { git_smart_subtransport parent; transport_smart *owner; http_server server; http_server proxy; git_http_client *http_client; } http_subtransport; static const http_service upload_pack_ls_service = { GIT_HTTP_METHOD_GET, "/info/refs?service=git-upload-pack", NULL, "application/x-git-upload-pack-advertisement", 0 }; static const http_service upload_pack_service = { GIT_HTTP_METHOD_POST, "/git-upload-pack", "application/x-git-upload-pack-request", "application/x-git-upload-pack-result", 0 }; static const http_service receive_pack_ls_service = { GIT_HTTP_METHOD_GET, "/info/refs?service=git-receive-pack", NULL, "application/x-git-receive-pack-advertisement", 0 }; static const http_service receive_pack_service = { GIT_HTTP_METHOD_POST, "/git-receive-pack", "application/x-git-receive-pack-request", "application/x-git-receive-pack-result", 1 }; #define SERVER_TYPE_REMOTE "remote" #define SERVER_TYPE_PROXY "proxy" #define OWNING_SUBTRANSPORT(s) ((http_subtransport *)(s)->parent.subtransport) static int apply_url_credentials( git_credential **cred, unsigned int allowed_types, const char *username, const char *password) { GIT_ASSERT_ARG(username); if (!password) password = ""; if (allowed_types & GIT_CREDENTIAL_USERPASS_PLAINTEXT) return git_credential_userpass_plaintext_new(cred, username, password); if ((allowed_types & GIT_CREDENTIAL_DEFAULT) && *username == '\0' && *password == '\0') return git_credential_default_new(cred); return GIT_PASSTHROUGH; } GIT_INLINE(void) free_cred(git_credential **cred) { if (*cred) { git_credential_free(*cred); (*cred) = NULL; } } static int handle_auth( http_server *server, const char *server_type, const char *url, unsigned int allowed_schemetypes, unsigned int allowed_credtypes, git_credential_acquire_cb callback, void *callback_payload) { int error = 1; if (server->cred) free_cred(&server->cred); /* Start with URL-specified credentials, if there were any. */ if ((allowed_credtypes & GIT_CREDENTIAL_USERPASS_PLAINTEXT) && !server->url_cred_presented && server->url.username) { error = apply_url_credentials(&server->cred, allowed_credtypes, server->url.username, server->url.password); server->url_cred_presented = 1; /* treat GIT_PASSTHROUGH as if callback isn't set */ if (error == GIT_PASSTHROUGH) error = 1; } if (error > 0 && callback) { error = callback(&server->cred, url, server->url.username, allowed_credtypes, callback_payload); /* treat GIT_PASSTHROUGH as if callback isn't set */ if (error == GIT_PASSTHROUGH) error = 1; } if (error > 0) { git_error_set(GIT_ERROR_HTTP, "%s authentication required but no callback set", server_type); error = GIT_EAUTH; } if (!error) server->auth_schemetypes = allowed_schemetypes; return error; } GIT_INLINE(int) handle_remote_auth( http_stream *stream, git_http_response *response) { http_subtransport *transport = OWNING_SUBTRANSPORT(stream); if (response->server_auth_credtypes == 0) { git_error_set(GIT_ERROR_HTTP, "server requires authentication that we do not support"); return GIT_EAUTH; } /* Otherwise, prompt for credentials. */ return handle_auth( &transport->server, SERVER_TYPE_REMOTE, transport->owner->url, response->server_auth_schemetypes, response->server_auth_credtypes, transport->owner->cred_acquire_cb, transport->owner->cred_acquire_payload); } GIT_INLINE(int) handle_proxy_auth( http_stream *stream, git_http_response *response) { http_subtransport *transport = OWNING_SUBTRANSPORT(stream); if (response->proxy_auth_credtypes == 0) { git_error_set(GIT_ERROR_HTTP, "proxy requires authentication that we do not support"); return GIT_EAUTH; } /* Otherwise, prompt for credentials. */ return handle_auth( &transport->proxy, SERVER_TYPE_PROXY, transport->owner->proxy.url, response->server_auth_schemetypes, response->proxy_auth_credtypes, transport->owner->proxy.credentials, transport->owner->proxy.payload); } static int handle_response( bool *complete, http_stream *stream, git_http_response *response, bool allow_replay) { http_subtransport *transport = OWNING_SUBTRANSPORT(stream); int error; *complete = false; if (allow_replay && git_http_response_is_redirect(response)) { if (!response->location) { git_error_set(GIT_ERROR_HTTP, "redirect without location"); return -1; } if (git_net_url_apply_redirect(&transport->server.url, response->location, stream->service->url) < 0) { return -1; } return 0; } else if (git_http_response_is_redirect(response)) { git_error_set(GIT_ERROR_HTTP, "unexpected redirect"); return -1; } /* If we're in the middle of challenge/response auth, continue. */ if (allow_replay && response->resend_credentials) { return 0; } else if (allow_replay && response->status == GIT_HTTP_STATUS_UNAUTHORIZED) { if ((error = handle_remote_auth(stream, response)) < 0) return error; return git_http_client_skip_body(transport->http_client); } else if (allow_replay && response->status == GIT_HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED) { if ((error = handle_proxy_auth(stream, response)) < 0) return error; return git_http_client_skip_body(transport->http_client); } else if (response->status == GIT_HTTP_STATUS_UNAUTHORIZED || response->status == GIT_HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED) { git_error_set(GIT_ERROR_HTTP, "unexpected authentication failure"); return GIT_EAUTH; } if (response->status != GIT_HTTP_STATUS_OK) { git_error_set(GIT_ERROR_HTTP, "unexpected http status code: %d", response->status); return -1; } /* The response must contain a Content-Type header. */ if (!response->content_type) { git_error_set(GIT_ERROR_HTTP, "no content-type header in response"); return -1; } /* The Content-Type header must match our expectation. */ if (strcmp(response->content_type, stream->service->response_type) != 0) { git_error_set(GIT_ERROR_HTTP, "invalid content-type: '%s'", response->content_type); return -1; } *complete = true; stream->state = HTTP_STATE_RECEIVING_RESPONSE; return 0; } static int lookup_proxy( bool *out_use, http_subtransport *transport) { const char *proxy; git_remote *remote; char *config = NULL; int error = 0; *out_use = false; git_net_url_dispose(&transport->proxy.url); switch (transport->owner->proxy.type) { case GIT_PROXY_SPECIFIED: proxy = transport->owner->proxy.url; break; case GIT_PROXY_AUTO: remote = transport->owner->owner; error = git_remote__http_proxy(&config, remote, &transport->server.url); if (error || !config) goto done; proxy = config; break; default: return 0; } if (!proxy || (error = git_net_url_parse(&transport->proxy.url, proxy)) < 0) goto done; *out_use = true; done: git__free(config); return error; } static int generate_request( git_net_url *url, git_http_request *request, http_stream *stream, size_t len) { http_subtransport *transport = OWNING_SUBTRANSPORT(stream); bool use_proxy = false; int error; if ((error = git_net_url_joinpath(url, &transport->server.url, stream->service->url)) < 0 || (error = lookup_proxy(&use_proxy, transport)) < 0) return error; request->method = stream->service->method; request->url = url; request->credentials = transport->server.cred; request->proxy = use_proxy ? &transport->proxy.url : NULL; request->proxy_credentials = transport->proxy.cred; request->custom_headers = &transport->owner->custom_headers; if (stream->service->method == GIT_HTTP_METHOD_POST) { request->chunked = stream->service->chunked; request->content_length = stream->service->chunked ? 0 : len; request->content_type = stream->service->request_type; request->accept = stream->service->response_type; request->expect_continue = git_http__expect_continue; } return 0; } /* * Read from an HTTP transport - for the first invocation of this function * (ie, when stream->state == HTTP_STATE_NONE), we'll send a GET request * to the remote host. We will stream that data back on all subsequent * calls. */ static int http_stream_read( git_smart_subtransport_stream *s, char *buffer, size_t buffer_size, size_t *out_len) { http_stream *stream = (http_stream *)s; http_subtransport *transport = OWNING_SUBTRANSPORT(stream); git_net_url url = GIT_NET_URL_INIT; git_net_url proxy_url = GIT_NET_URL_INIT; git_http_request request = {0}; git_http_response response = {0}; bool complete; int error; *out_len = 0; if (stream->state == HTTP_STATE_NONE) { stream->state = HTTP_STATE_SENDING_REQUEST; stream->replay_count = 0; } /* * Formulate the URL, send the request and read the response * headers. Some of the request body may also be read. */ while (stream->state == HTTP_STATE_SENDING_REQUEST && stream->replay_count < GIT_HTTP_REPLAY_MAX) { git_net_url_dispose(&url); git_net_url_dispose(&proxy_url); git_http_response_dispose(&response); if ((error = generate_request(&url, &request, stream, 0)) < 0 || (error = git_http_client_send_request( transport->http_client, &request)) < 0 || (error = git_http_client_read_response( &response, transport->http_client)) < 0 || (error = handle_response(&complete, stream, &response, true)) < 0) goto done; if (complete) break; stream->replay_count++; } if (stream->state == HTTP_STATE_SENDING_REQUEST) { git_error_set(GIT_ERROR_HTTP, "too many redirects or authentication replays"); error = GIT_ERROR; /* not GIT_EAUTH, because the exact cause is unclear */ goto done; } GIT_ASSERT(stream->state == HTTP_STATE_RECEIVING_RESPONSE); error = git_http_client_read_body(transport->http_client, buffer, buffer_size); if (error > 0) { *out_len = error; error = 0; } done: git_net_url_dispose(&url); git_net_url_dispose(&proxy_url); git_http_response_dispose(&response); return error; } static bool needs_probe(http_stream *stream) { http_subtransport *transport = OWNING_SUBTRANSPORT(stream); return (transport->server.auth_schemetypes == GIT_HTTP_AUTH_NTLM || transport->server.auth_schemetypes == GIT_HTTP_AUTH_NEGOTIATE); } static int send_probe(http_stream *stream) { http_subtransport *transport = OWNING_SUBTRANSPORT(stream); git_http_client *client = transport->http_client; const char *probe = "0000"; size_t len = 4; git_net_url url = GIT_NET_URL_INIT; git_http_request request = {0}; git_http_response response = {0}; bool complete = false; size_t step, steps = 1; int error; /* NTLM requires a full challenge/response */ if (transport->server.auth_schemetypes == GIT_HTTP_AUTH_NTLM) steps = GIT_AUTH_STEPS_NTLM; /* * Send at most two requests: one without any authentication to see * if we get prompted to authenticate. If we do, send a second one * with the first authentication message. The final authentication * message with the response will occur with the *actual* POST data. */ for (step = 0; step < steps && !complete; step++) { git_net_url_dispose(&url); git_http_response_dispose(&response); if ((error = generate_request(&url, &request, stream, len)) < 0 || (error = git_http_client_send_request(client, &request)) < 0 || (error = git_http_client_send_body(client, probe, len)) < 0 || (error = git_http_client_read_response(&response, client)) < 0 || (error = git_http_client_skip_body(client)) < 0 || (error = handle_response(&complete, stream, &response, true)) < 0) goto done; } done: git_http_response_dispose(&response); git_net_url_dispose(&url); return error; } /* * Write to an HTTP transport - for the first invocation of this function * (ie, when stream->state == HTTP_STATE_NONE), we'll send a POST request * to the remote host. If we're sending chunked data, then subsequent calls * will write the additional data given in the buffer. If we're not chunking, * then the caller should have given us all the data in the original call. * The caller should call http_stream_read_response to get the result. */ static int http_stream_write( git_smart_subtransport_stream *s, const char *buffer, size_t len) { http_stream *stream = GIT_CONTAINER_OF(s, http_stream, parent); http_subtransport *transport = OWNING_SUBTRANSPORT(stream); git_net_url url = GIT_NET_URL_INIT; git_http_request request = {0}; git_http_response response = {0}; int error; while (stream->state == HTTP_STATE_NONE && stream->replay_count < GIT_HTTP_REPLAY_MAX) { git_net_url_dispose(&url); git_http_response_dispose(&response); /* * If we're authenticating with a connection-based mechanism * (NTLM, Kerberos), send a "probe" packet. Servers SHOULD * authenticate an entire keep-alive connection, so ideally * we should not need to authenticate but some servers do * not support this. By sending a probe packet, we'll be * able to follow up with a second POST using the actual * data (and, in the degenerate case, the authentication * header as well). */ if (needs_probe(stream) && (error = send_probe(stream)) < 0) goto done; /* Send the regular POST request. */ if ((error = generate_request(&url, &request, stream, len)) < 0 || (error = git_http_client_send_request( transport->http_client, &request)) < 0) goto done; if (request.expect_continue && git_http_client_has_response(transport->http_client)) { bool complete; /* * If we got a response to an expect/continue, then * it's something other than a 100 and we should * deal with the response somehow. */ if ((error = git_http_client_read_response(&response, transport->http_client)) < 0 || (error = handle_response(&complete, stream, &response, true)) < 0) goto done; } else { stream->state = HTTP_STATE_SENDING_REQUEST; } stream->replay_count++; } if (stream->state == HTTP_STATE_NONE) { git_error_set(GIT_ERROR_HTTP, "too many redirects or authentication replays"); error = GIT_ERROR; /* not GIT_EAUTH because the exact cause is unclear */ goto done; } GIT_ASSERT(stream->state == HTTP_STATE_SENDING_REQUEST); error = git_http_client_send_body(transport->http_client, buffer, len); done: git_http_response_dispose(&response); git_net_url_dispose(&url); return error; } /* * Read from an HTTP transport after it has been written to. This is the * response from a POST request made by http_stream_write. */ static int http_stream_read_response( git_smart_subtransport_stream *s, char *buffer, size_t buffer_size, size_t *out_len) { http_stream *stream = (http_stream *)s; http_subtransport *transport = OWNING_SUBTRANSPORT(stream); git_http_client *client = transport->http_client; git_http_response response = {0}; bool complete; int error; *out_len = 0; if (stream->state == HTTP_STATE_SENDING_REQUEST) { if ((error = git_http_client_read_response(&response, client)) < 0 || (error = handle_response(&complete, stream, &response, false)) < 0) goto done; GIT_ASSERT(complete); stream->state = HTTP_STATE_RECEIVING_RESPONSE; } error = git_http_client_read_body(client, buffer, buffer_size); if (error > 0) { *out_len = error; error = 0; } done: git_http_response_dispose(&response); return error; } static void http_stream_free(git_smart_subtransport_stream *stream) { http_stream *s = GIT_CONTAINER_OF(stream, http_stream, parent); git__free(s); } static const http_service *select_service(git_smart_service_t action) { switch (action) { case GIT_SERVICE_UPLOADPACK_LS: return &upload_pack_ls_service; case GIT_SERVICE_UPLOADPACK: return &upload_pack_service; case GIT_SERVICE_RECEIVEPACK_LS: return &receive_pack_ls_service; case GIT_SERVICE_RECEIVEPACK: return &receive_pack_service; } return NULL; } static int http_action( git_smart_subtransport_stream **out, git_smart_subtransport *t, const char *url, git_smart_service_t action) { http_subtransport *transport = GIT_CONTAINER_OF(t, http_subtransport, parent); http_stream *stream; const http_service *service; int error; GIT_ASSERT_ARG(out); GIT_ASSERT_ARG(t); *out = NULL; /* * If we've seen a redirect then preserve the location that we've * been given. This is important to continue authorization against * the redirect target, not the user-given source; the endpoint may * have redirected us from HTTP->HTTPS and is using an auth mechanism * that would be insecure in plaintext (eg, HTTP Basic). */ if (!git_net_url_valid(&transport->server.url) && (error = git_net_url_parse(&transport->server.url, url)) < 0) return error; if ((service = select_service(action)) == NULL) { git_error_set(GIT_ERROR_HTTP, "invalid action"); return -1; } stream = git__calloc(sizeof(http_stream), 1); GIT_ERROR_CHECK_ALLOC(stream); if (!transport->http_client) { git_http_client_options opts = {0}; opts.server_certificate_check_cb = transport->owner->certificate_check_cb; opts.server_certificate_check_payload = transport->owner->message_cb_payload; opts.proxy_certificate_check_cb = transport->owner->proxy.certificate_check; opts.proxy_certificate_check_payload = transport->owner->proxy.payload; if (git_http_client_new(&transport->http_client, &opts) < 0) return -1; } stream->service = service; stream->parent.subtransport = &transport->parent; if (service->method == GIT_HTTP_METHOD_GET) { stream->parent.read = http_stream_read; } else { stream->parent.write = http_stream_write; stream->parent.read = http_stream_read_response; } stream->parent.free = http_stream_free; *out = (git_smart_subtransport_stream *)stream; return 0; } static int http_close(git_smart_subtransport *t) { http_subtransport *transport = GIT_CONTAINER_OF(t, http_subtransport, parent); free_cred(&transport->server.cred); free_cred(&transport->proxy.cred); transport->server.url_cred_presented = false; transport->proxy.url_cred_presented = false; git_net_url_dispose(&transport->server.url); git_net_url_dispose(&transport->proxy.url); return 0; } static void http_free(git_smart_subtransport *t) { http_subtransport *transport = GIT_CONTAINER_OF(t, http_subtransport, parent); git_http_client_free(transport->http_client); http_close(t); git__free(transport); } int git_smart_subtransport_http(git_smart_subtransport **out, git_transport *owner, void *param) { http_subtransport *transport; GIT_UNUSED(param); GIT_ASSERT_ARG(out); transport = git__calloc(sizeof(http_subtransport), 1); GIT_ERROR_CHECK_ALLOC(transport); transport->owner = (transport_smart *)owner; transport->parent.action = http_action; transport->parent.close = http_close; transport->parent.free = http_free; *out = (git_smart_subtransport *) transport; return 0; } #endif /* !GIT_WINHTTP */
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/transports/smart.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "smart.h" #include "git2.h" #include "refs.h" #include "refspec.h" #include "proxy.h" static int git_smart__recv_cb(gitno_buffer *buf) { transport_smart *t = (transport_smart *) buf->cb_data; size_t old_len, bytes_read; int error; GIT_ASSERT(t->current_stream); old_len = buf->offset; if ((error = t->current_stream->read(t->current_stream, buf->data + buf->offset, buf->len - buf->offset, &bytes_read)) < 0) return error; buf->offset += bytes_read; if (t->packetsize_cb && !t->cancelled.val) { error = t->packetsize_cb(bytes_read, t->packetsize_payload); if (error) { git_atomic32_set(&t->cancelled, 1); return GIT_EUSER; } } return (int)(buf->offset - old_len); } GIT_INLINE(int) git_smart__reset_stream(transport_smart *t, bool close_subtransport) { if (t->current_stream) { t->current_stream->free(t->current_stream); t->current_stream = NULL; } if (close_subtransport) { git__free(t->url); t->url = NULL; if (t->wrapped->close(t->wrapped) < 0) return -1; } return 0; } static int git_smart__set_callbacks( git_transport *transport, git_transport_message_cb progress_cb, git_transport_message_cb error_cb, git_transport_certificate_check_cb certificate_check_cb, void *message_cb_payload) { transport_smart *t = GIT_CONTAINER_OF(transport, transport_smart, parent); t->progress_cb = progress_cb; t->error_cb = error_cb; t->certificate_check_cb = certificate_check_cb; t->message_cb_payload = message_cb_payload; return 0; } static size_t http_header_name_length(const char *http_header) { const char *colon = strchr(http_header, ':'); if (!colon) return 0; return colon - http_header; } static bool is_malformed_http_header(const char *http_header) { const char *c; size_t name_len; /* Disallow \r and \n */ c = strchr(http_header, '\r'); if (c) return true; c = strchr(http_header, '\n'); if (c) return true; /* Require a header name followed by : */ name_len = http_header_name_length(http_header); if (name_len < 1) return true; return false; } static char *forbidden_custom_headers[] = { "User-Agent", "Host", "Accept", "Content-Type", "Transfer-Encoding", "Content-Length", }; static bool is_forbidden_custom_header(const char *custom_header) { unsigned long i; size_t name_len = http_header_name_length(custom_header); /* Disallow headers that we set */ for (i = 0; i < ARRAY_SIZE(forbidden_custom_headers); i++) if (strncmp(forbidden_custom_headers[i], custom_header, name_len) == 0) return true; return false; } static int git_smart__set_custom_headers( git_transport *transport, const git_strarray *custom_headers) { transport_smart *t = GIT_CONTAINER_OF(transport, transport_smart, parent); size_t i; if (t->custom_headers.count) git_strarray_dispose(&t->custom_headers); if (!custom_headers) return 0; for (i = 0; i < custom_headers->count; i++) { if (is_malformed_http_header(custom_headers->strings[i])) { git_error_set(GIT_ERROR_INVALID, "custom HTTP header '%s' is malformed", custom_headers->strings[i]); return -1; } if (is_forbidden_custom_header(custom_headers->strings[i])) { git_error_set(GIT_ERROR_INVALID, "custom HTTP header '%s' is already set by libgit2", custom_headers->strings[i]); return -1; } } return git_strarray_copy(&t->custom_headers, custom_headers); } int git_smart__update_heads(transport_smart *t, git_vector *symrefs) { size_t i; git_pkt *pkt; git_vector_clear(&t->heads); git_vector_foreach(&t->refs, i, pkt) { git_pkt_ref *ref = (git_pkt_ref *) pkt; if (pkt->type != GIT_PKT_REF) continue; if (symrefs) { git_refspec *spec; git_buf buf = GIT_BUF_INIT; size_t j; int error = 0; git_vector_foreach(symrefs, j, spec) { git_buf_clear(&buf); if (git_refspec_src_matches(spec, ref->head.name) && !(error = git_refspec_transform(&buf, spec, ref->head.name))) { git__free(ref->head.symref_target); ref->head.symref_target = git_buf_detach(&buf); } } git_buf_dispose(&buf); if (error < 0) return error; } if (git_vector_insert(&t->heads, &ref->head) < 0) return -1; } return 0; } static void free_symrefs(git_vector *symrefs) { git_refspec *spec; size_t i; git_vector_foreach(symrefs, i, spec) { git_refspec__dispose(spec); git__free(spec); } git_vector_free(symrefs); } static int git_smart__connect( git_transport *transport, const char *url, git_credential_acquire_cb cred_acquire_cb, void *cred_acquire_payload, const git_proxy_options *proxy, int direction, int flags) { transport_smart *t = GIT_CONTAINER_OF(transport, transport_smart, parent); git_smart_subtransport_stream *stream; int error; git_pkt *pkt; git_pkt_ref *first; git_vector symrefs; git_smart_service_t service; if (git_smart__reset_stream(t, true) < 0) return -1; t->url = git__strdup(url); GIT_ERROR_CHECK_ALLOC(t->url); git_proxy_options_clear(&t->proxy); if (git_proxy_options_dup(&t->proxy, proxy) < 0) return -1; t->direction = direction; t->flags = flags; t->cred_acquire_cb = cred_acquire_cb; t->cred_acquire_payload = cred_acquire_payload; if (GIT_DIRECTION_FETCH == t->direction) service = GIT_SERVICE_UPLOADPACK_LS; else if (GIT_DIRECTION_PUSH == t->direction) service = GIT_SERVICE_RECEIVEPACK_LS; else { git_error_set(GIT_ERROR_NET, "invalid direction"); return -1; } if ((error = t->wrapped->action(&stream, t->wrapped, t->url, service)) < 0) return error; /* Save off the current stream (i.e. socket) that we are working with */ t->current_stream = stream; gitno_buffer_setup_callback(&t->buffer, t->buffer_data, sizeof(t->buffer_data), git_smart__recv_cb, t); /* 2 flushes for RPC; 1 for stateful */ if ((error = git_smart__store_refs(t, t->rpc ? 2 : 1)) < 0) return error; /* Strip the comment packet for RPC */ if (t->rpc) { pkt = (git_pkt *)git_vector_get(&t->refs, 0); if (!pkt || GIT_PKT_COMMENT != pkt->type) { git_error_set(GIT_ERROR_NET, "invalid response"); return -1; } else { /* Remove the comment pkt from the list */ git_vector_remove(&t->refs, 0); git__free(pkt); } } /* We now have loaded the refs. */ t->have_refs = 1; pkt = (git_pkt *)git_vector_get(&t->refs, 0); if (pkt && GIT_PKT_REF != pkt->type) { git_error_set(GIT_ERROR_NET, "invalid response"); return -1; } first = (git_pkt_ref *)pkt; if ((error = git_vector_init(&symrefs, 1, NULL)) < 0) return error; /* Detect capabilities */ if ((error = git_smart__detect_caps(first, &t->caps, &symrefs)) == 0) { /* If the only ref in the list is capabilities^{} with OID_ZERO, remove it */ if (1 == t->refs.length && !strcmp(first->head.name, "capabilities^{}") && git_oid_is_zero(&first->head.oid)) { git_vector_clear(&t->refs); git_pkt_free((git_pkt *)first); } /* Keep a list of heads for _ls */ git_smart__update_heads(t, &symrefs); } else if (error == GIT_ENOTFOUND) { /* There was no ref packet received, or the cap list was empty */ error = 0; } else { git_error_set(GIT_ERROR_NET, "invalid response"); goto cleanup; } if (t->rpc && (error = git_smart__reset_stream(t, false)) < 0) goto cleanup; /* We're now logically connected. */ t->connected = 1; cleanup: free_symrefs(&symrefs); return error; } static int git_smart__ls(const git_remote_head ***out, size_t *size, git_transport *transport) { transport_smart *t = GIT_CONTAINER_OF(transport, transport_smart, parent); if (!t->have_refs) { git_error_set(GIT_ERROR_NET, "the transport has not yet loaded the refs"); return -1; } *out = (const git_remote_head **) t->heads.contents; *size = t->heads.length; return 0; } int git_smart__negotiation_step(git_transport *transport, void *data, size_t len) { transport_smart *t = GIT_CONTAINER_OF(transport, transport_smart, parent); git_smart_subtransport_stream *stream; int error; if (t->rpc && git_smart__reset_stream(t, false) < 0) return -1; if (GIT_DIRECTION_FETCH != t->direction) { git_error_set(GIT_ERROR_NET, "this operation is only valid for fetch"); return -1; } if ((error = t->wrapped->action(&stream, t->wrapped, t->url, GIT_SERVICE_UPLOADPACK)) < 0) return error; /* If this is a stateful implementation, the stream we get back should be the same */ GIT_ASSERT(t->rpc || t->current_stream == stream); /* Save off the current stream (i.e. socket) that we are working with */ t->current_stream = stream; if ((error = stream->write(stream, (const char *)data, len)) < 0) return error; gitno_buffer_setup_callback(&t->buffer, t->buffer_data, sizeof(t->buffer_data), git_smart__recv_cb, t); return 0; } int git_smart__get_push_stream(transport_smart *t, git_smart_subtransport_stream **stream) { int error; if (t->rpc && git_smart__reset_stream(t, false) < 0) return -1; if (GIT_DIRECTION_PUSH != t->direction) { git_error_set(GIT_ERROR_NET, "this operation is only valid for push"); return -1; } if ((error = t->wrapped->action(stream, t->wrapped, t->url, GIT_SERVICE_RECEIVEPACK)) < 0) return error; /* If this is a stateful implementation, the stream we get back should be the same */ GIT_ASSERT(t->rpc || t->current_stream == *stream); /* Save off the current stream (i.e. socket) that we are working with */ t->current_stream = *stream; gitno_buffer_setup_callback(&t->buffer, t->buffer_data, sizeof(t->buffer_data), git_smart__recv_cb, t); return 0; } static void git_smart__cancel(git_transport *transport) { transport_smart *t = GIT_CONTAINER_OF(transport, transport_smart, parent); git_atomic32_set(&t->cancelled, 1); } static int git_smart__is_connected(git_transport *transport) { transport_smart *t = GIT_CONTAINER_OF(transport, transport_smart, parent); return t->connected; } static int git_smart__read_flags(git_transport *transport, int *flags) { transport_smart *t = GIT_CONTAINER_OF(transport, transport_smart, parent); *flags = t->flags; return 0; } static int git_smart__close(git_transport *transport) { transport_smart *t = GIT_CONTAINER_OF(transport, transport_smart, parent); git_vector *common = &t->common; unsigned int i; git_pkt *p; int ret; git_smart_subtransport_stream *stream; const char flush[] = "0000"; /* * If we're still connected at this point and not using RPC, * we should say goodbye by sending a flush, or git-daemon * will complain that we disconnected unexpectedly. */ if (t->connected && !t->rpc && !t->wrapped->action(&stream, t->wrapped, t->url, GIT_SERVICE_UPLOADPACK)) { t->current_stream->write(t->current_stream, flush, 4); } ret = git_smart__reset_stream(t, true); git_vector_foreach(common, i, p) git_pkt_free(p); git_vector_free(common); if (t->url) { git__free(t->url); t->url = NULL; } t->connected = 0; return ret; } static void git_smart__free(git_transport *transport) { transport_smart *t = GIT_CONTAINER_OF(transport, transport_smart, parent); git_vector *refs = &t->refs; unsigned int i; git_pkt *p; /* Make sure that the current stream is closed, if we have one. */ git_smart__close(transport); /* Free the subtransport */ t->wrapped->free(t->wrapped); git_vector_free(&t->heads); git_vector_foreach(refs, i, p) git_pkt_free(p); git_vector_free(refs); git__free((char *)t->proxy.url); git_strarray_dispose(&t->custom_headers); git__free(t); } static int ref_name_cmp(const void *a, const void *b) { const git_pkt_ref *ref_a = a, *ref_b = b; return strcmp(ref_a->head.name, ref_b->head.name); } int git_transport_smart_certificate_check(git_transport *transport, git_cert *cert, int valid, const char *hostname) { transport_smart *t = GIT_CONTAINER_OF(transport, transport_smart, parent); GIT_ASSERT_ARG(transport); GIT_ASSERT_ARG(cert); GIT_ASSERT_ARG(hostname); if (!t->certificate_check_cb) return GIT_PASSTHROUGH; return t->certificate_check_cb(cert, valid, hostname, t->message_cb_payload); } int git_transport_smart_credentials(git_credential **out, git_transport *transport, const char *user, int methods) { transport_smart *t = GIT_CONTAINER_OF(transport, transport_smart, parent); GIT_ASSERT_ARG(out); GIT_ASSERT_ARG(transport); if (!t->cred_acquire_cb) return GIT_PASSTHROUGH; return t->cred_acquire_cb(out, t->url, user, methods, t->cred_acquire_payload); } int git_transport_smart_proxy_options(git_proxy_options *out, git_transport *transport) { transport_smart *t = GIT_CONTAINER_OF(transport, transport_smart, parent); return git_proxy_options_dup(out, &t->proxy); } int git_transport_smart(git_transport **out, git_remote *owner, void *param) { transport_smart *t; git_smart_subtransport_definition *definition = (git_smart_subtransport_definition *)param; if (!param) return -1; t = git__calloc(1, sizeof(transport_smart)); GIT_ERROR_CHECK_ALLOC(t); t->parent.version = GIT_TRANSPORT_VERSION; t->parent.set_callbacks = git_smart__set_callbacks; t->parent.set_custom_headers = git_smart__set_custom_headers; t->parent.connect = git_smart__connect; t->parent.close = git_smart__close; t->parent.free = git_smart__free; t->parent.negotiate_fetch = git_smart__negotiate_fetch; t->parent.download_pack = git_smart__download_pack; t->parent.push = git_smart__push; t->parent.ls = git_smart__ls; t->parent.is_connected = git_smart__is_connected; t->parent.read_flags = git_smart__read_flags; t->parent.cancel = git_smart__cancel; t->owner = owner; t->rpc = definition->rpc; if (git_vector_init(&t->refs, 16, ref_name_cmp) < 0) { git__free(t); return -1; } if (git_vector_init(&t->heads, 16, ref_name_cmp) < 0) { git__free(t); return -1; } if (definition->callback(&t->wrapped, &t->parent, definition->param) < 0) { git__free(t); return -1; } *out = (git_transport *) t; return 0; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/transports/httpclient.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "common.h" #include "git2.h" #include "http_parser.h" #include "vector.h" #include "trace.h" #include "httpclient.h" #include "http.h" #include "auth.h" #include "auth_negotiate.h" #include "auth_ntlm.h" #include "git2/sys/credential.h" #include "net.h" #include "stream.h" #include "streams/socket.h" #include "streams/tls.h" #include "auth.h" static git_http_auth_scheme auth_schemes[] = { { GIT_HTTP_AUTH_NEGOTIATE, "Negotiate", GIT_CREDENTIAL_DEFAULT, git_http_auth_negotiate }, { GIT_HTTP_AUTH_NTLM, "NTLM", GIT_CREDENTIAL_USERPASS_PLAINTEXT, git_http_auth_ntlm }, { GIT_HTTP_AUTH_BASIC, "Basic", GIT_CREDENTIAL_USERPASS_PLAINTEXT, git_http_auth_basic }, }; /* * Use a 16kb read buffer to match the maximum size of a TLS packet. This * is critical for compatibility with SecureTransport, which will always do * a network read on every call, even if it has data buffered to return to * you. That buffered data may be the _end_ of a keep-alive response, so * if SecureTransport performs another network read, it will wait until the * server ultimately times out before it returns that buffered data to you. * Since SecureTransport only reads a single TLS packet at a time, by * calling it with a read buffer that is the maximum size of a TLS packet, * we ensure that it will never buffer. */ #define GIT_READ_BUFFER_SIZE (16 * 1024) typedef struct { git_net_url url; git_stream *stream; git_vector auth_challenges; git_http_auth_context *auth_context; } git_http_server; typedef enum { PROXY = 1, SERVER } git_http_server_t; typedef enum { NONE = 0, SENDING_REQUEST, SENDING_BODY, SENT_REQUEST, HAS_EARLY_RESPONSE, READING_RESPONSE, READING_BODY, DONE } http_client_state; /* Parser state */ typedef enum { PARSE_HEADER_NONE = 0, PARSE_HEADER_NAME, PARSE_HEADER_VALUE, PARSE_HEADER_COMPLETE } parse_header_state; typedef enum { PARSE_STATUS_OK, PARSE_STATUS_NO_OUTPUT, PARSE_STATUS_ERROR } parse_status; typedef struct { git_http_client *client; git_http_response *response; /* Temporary buffers to avoid extra mallocs */ git_buf parse_header_name; git_buf parse_header_value; /* Parser state */ int error; parse_status parse_status; /* Headers parsing */ parse_header_state parse_header_state; /* Body parsing */ char *output_buf; /* Caller's output buffer */ size_t output_size; /* Size of caller's output buffer */ size_t output_written; /* Bytes we've written to output buffer */ } http_parser_context; /* HTTP client connection */ struct git_http_client { git_http_client_options opts; /* Are we writing to the proxy or server, and state of the client. */ git_http_server_t current_server; http_client_state state; http_parser parser; git_http_server server; git_http_server proxy; unsigned request_count; unsigned connected : 1, proxy_connected : 1, keepalive : 1, request_chunked : 1; /* Temporary buffers to avoid extra mallocs */ git_buf request_msg; git_buf read_buf; /* A subset of information from the request */ size_t request_body_len, request_body_remain; /* * When state == HAS_EARLY_RESPONSE, the response of our proxy * that we have buffered and will deliver during read_response. */ git_http_response early_response; }; bool git_http_response_is_redirect(git_http_response *response) { return (response->status == GIT_HTTP_MOVED_PERMANENTLY || response->status == GIT_HTTP_FOUND || response->status == GIT_HTTP_SEE_OTHER || response->status == GIT_HTTP_TEMPORARY_REDIRECT || response->status == GIT_HTTP_PERMANENT_REDIRECT); } void git_http_response_dispose(git_http_response *response) { if (!response) return; git__free(response->content_type); git__free(response->location); memset(response, 0, sizeof(git_http_response)); } static int on_header_complete(http_parser *parser) { http_parser_context *ctx = (http_parser_context *) parser->data; git_http_client *client = ctx->client; git_http_response *response = ctx->response; git_buf *name = &ctx->parse_header_name; git_buf *value = &ctx->parse_header_value; if (!strcasecmp("Content-Type", name->ptr)) { if (response->content_type) { git_error_set(GIT_ERROR_HTTP, "multiple content-type headers"); return -1; } response->content_type = git__strndup(value->ptr, value->size); GIT_ERROR_CHECK_ALLOC(ctx->response->content_type); } else if (!strcasecmp("Content-Length", name->ptr)) { int64_t len; if (response->content_length) { git_error_set(GIT_ERROR_HTTP, "multiple content-length headers"); return -1; } if (git__strntol64(&len, value->ptr, value->size, NULL, 10) < 0 || len < 0) { git_error_set(GIT_ERROR_HTTP, "invalid content-length"); return -1; } response->content_length = (size_t)len; } else if (!strcasecmp("Transfer-Encoding", name->ptr) && !strcasecmp("chunked", value->ptr)) { ctx->response->chunked = 1; } else if (!strcasecmp("Proxy-Authenticate", git_buf_cstr(name))) { char *dup = git__strndup(value->ptr, value->size); GIT_ERROR_CHECK_ALLOC(dup); if (git_vector_insert(&client->proxy.auth_challenges, dup) < 0) return -1; } else if (!strcasecmp("WWW-Authenticate", name->ptr)) { char *dup = git__strndup(value->ptr, value->size); GIT_ERROR_CHECK_ALLOC(dup); if (git_vector_insert(&client->server.auth_challenges, dup) < 0) return -1; } else if (!strcasecmp("Location", name->ptr)) { if (response->location) { git_error_set(GIT_ERROR_HTTP, "multiple location headers"); return -1; } response->location = git__strndup(value->ptr, value->size); GIT_ERROR_CHECK_ALLOC(response->location); } return 0; } static int on_header_field(http_parser *parser, const char *str, size_t len) { http_parser_context *ctx = (http_parser_context *) parser->data; switch (ctx->parse_header_state) { /* * We last saw a header value, process the name/value pair and * get ready to handle this new name. */ case PARSE_HEADER_VALUE: if (on_header_complete(parser) < 0) return ctx->parse_status = PARSE_STATUS_ERROR; git_buf_clear(&ctx->parse_header_name); git_buf_clear(&ctx->parse_header_value); /* Fall through */ case PARSE_HEADER_NONE: case PARSE_HEADER_NAME: ctx->parse_header_state = PARSE_HEADER_NAME; if (git_buf_put(&ctx->parse_header_name, str, len) < 0) return ctx->parse_status = PARSE_STATUS_ERROR; break; default: git_error_set(GIT_ERROR_HTTP, "header name seen at unexpected time"); return ctx->parse_status = PARSE_STATUS_ERROR; } return 0; } static int on_header_value(http_parser *parser, const char *str, size_t len) { http_parser_context *ctx = (http_parser_context *) parser->data; switch (ctx->parse_header_state) { case PARSE_HEADER_NAME: case PARSE_HEADER_VALUE: ctx->parse_header_state = PARSE_HEADER_VALUE; if (git_buf_put(&ctx->parse_header_value, str, len) < 0) return ctx->parse_status = PARSE_STATUS_ERROR; break; default: git_error_set(GIT_ERROR_HTTP, "header value seen at unexpected time"); return ctx->parse_status = PARSE_STATUS_ERROR; } return 0; } GIT_INLINE(bool) challenge_matches_scheme( const char *challenge, git_http_auth_scheme *scheme) { const char *scheme_name = scheme->name; size_t scheme_len = strlen(scheme_name); if (!strncasecmp(challenge, scheme_name, scheme_len) && (challenge[scheme_len] == '\0' || challenge[scheme_len] == ' ')) return true; return false; } static git_http_auth_scheme *scheme_for_challenge(const char *challenge) { size_t i; for (i = 0; i < ARRAY_SIZE(auth_schemes); i++) { if (challenge_matches_scheme(challenge, &auth_schemes[i])) return &auth_schemes[i]; } return NULL; } GIT_INLINE(void) collect_authinfo( unsigned int *schemetypes, unsigned int *credtypes, git_vector *challenges) { git_http_auth_scheme *scheme; const char *challenge; size_t i; *schemetypes = 0; *credtypes = 0; git_vector_foreach(challenges, i, challenge) { if ((scheme = scheme_for_challenge(challenge)) != NULL) { *schemetypes |= scheme->type; *credtypes |= scheme->credtypes; } } } static int resend_needed(git_http_client *client, git_http_response *response) { git_http_auth_context *auth_context; if (response->status == GIT_HTTP_STATUS_UNAUTHORIZED && (auth_context = client->server.auth_context) && auth_context->is_complete && !auth_context->is_complete(auth_context)) return 1; if (response->status == GIT_HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED && (auth_context = client->proxy.auth_context) && auth_context->is_complete && !auth_context->is_complete(auth_context)) return 1; return 0; } static int on_headers_complete(http_parser *parser) { http_parser_context *ctx = (http_parser_context *) parser->data; /* Finalize the last seen header */ switch (ctx->parse_header_state) { case PARSE_HEADER_VALUE: if (on_header_complete(parser) < 0) return ctx->parse_status = PARSE_STATUS_ERROR; /* Fall through */ case PARSE_HEADER_NONE: ctx->parse_header_state = PARSE_HEADER_COMPLETE; break; default: git_error_set(GIT_ERROR_HTTP, "header completion at unexpected time"); return ctx->parse_status = PARSE_STATUS_ERROR; } ctx->response->status = parser->status_code; ctx->client->keepalive = http_should_keep_alive(parser); /* Prepare for authentication */ collect_authinfo(&ctx->response->server_auth_schemetypes, &ctx->response->server_auth_credtypes, &ctx->client->server.auth_challenges); collect_authinfo(&ctx->response->proxy_auth_schemetypes, &ctx->response->proxy_auth_credtypes, &ctx->client->proxy.auth_challenges); ctx->response->resend_credentials = resend_needed(ctx->client, ctx->response); /* Stop parsing. */ http_parser_pause(parser, 1); if (ctx->response->content_type || ctx->response->chunked) ctx->client->state = READING_BODY; else ctx->client->state = DONE; return 0; } static int on_body(http_parser *parser, const char *buf, size_t len) { http_parser_context *ctx = (http_parser_context *) parser->data; size_t max_len; /* Saw data when we expected not to (eg, in consume_response_body) */ if (ctx->output_buf == NULL && ctx->output_size == 0) { ctx->parse_status = PARSE_STATUS_NO_OUTPUT; return 0; } GIT_ASSERT(ctx->output_size >= ctx->output_written); max_len = min(ctx->output_size - ctx->output_written, len); max_len = min(max_len, INT_MAX); memcpy(ctx->output_buf + ctx->output_written, buf, max_len); ctx->output_written += max_len; return 0; } static int on_message_complete(http_parser *parser) { http_parser_context *ctx = (http_parser_context *) parser->data; ctx->client->state = DONE; return 0; } GIT_INLINE(int) stream_write( git_http_server *server, const char *data, size_t len) { git_trace(GIT_TRACE_TRACE, "Sending request:\n%.*s", (int)len, data); return git_stream__write_full(server->stream, data, len, 0); } GIT_INLINE(int) client_write_request(git_http_client *client) { git_stream *stream = client->current_server == PROXY ? client->proxy.stream : client->server.stream; git_trace(GIT_TRACE_TRACE, "Sending request:\n%.*s", (int)client->request_msg.size, client->request_msg.ptr); return git_stream__write_full(stream, client->request_msg.ptr, client->request_msg.size, 0); } static const char *name_for_method(git_http_method method) { switch (method) { case GIT_HTTP_METHOD_GET: return "GET"; case GIT_HTTP_METHOD_POST: return "POST"; case GIT_HTTP_METHOD_CONNECT: return "CONNECT"; } return NULL; } /* * Find the scheme that is suitable for the given credentials, based on the * server's auth challenges. */ static bool best_scheme_and_challenge( git_http_auth_scheme **scheme_out, const char **challenge_out, git_vector *challenges, git_credential *credentials) { const char *challenge; size_t i, j; for (i = 0; i < ARRAY_SIZE(auth_schemes); i++) { git_vector_foreach(challenges, j, challenge) { git_http_auth_scheme *scheme = &auth_schemes[i]; if (challenge_matches_scheme(challenge, scheme) && (scheme->credtypes & credentials->credtype)) { *scheme_out = scheme; *challenge_out = challenge; return true; } } } return false; } /* * Find the challenge from the server for our current auth context. */ static const char *challenge_for_context( git_vector *challenges, git_http_auth_context *auth_ctx) { const char *challenge; size_t i, j; for (i = 0; i < ARRAY_SIZE(auth_schemes); i++) { if (auth_schemes[i].type == auth_ctx->type) { git_http_auth_scheme *scheme = &auth_schemes[i]; git_vector_foreach(challenges, j, challenge) { if (challenge_matches_scheme(challenge, scheme)) return challenge; } } } return NULL; } static const char *init_auth_context( git_http_server *server, git_vector *challenges, git_credential *credentials) { git_http_auth_scheme *scheme; const char *challenge; int error; if (!best_scheme_and_challenge(&scheme, &challenge, challenges, credentials)) { git_error_set(GIT_ERROR_HTTP, "could not find appropriate mechanism for credentials"); return NULL; } error = scheme->init_context(&server->auth_context, &server->url); if (error == GIT_PASSTHROUGH) { git_error_set(GIT_ERROR_HTTP, "'%s' authentication is not supported", scheme->name); return NULL; } return challenge; } static void free_auth_context(git_http_server *server) { if (!server->auth_context) return; if (server->auth_context->free) server->auth_context->free(server->auth_context); server->auth_context = NULL; } static int apply_credentials( git_buf *buf, git_http_server *server, const char *header_name, git_credential *credentials) { git_http_auth_context *auth = server->auth_context; git_vector *challenges = &server->auth_challenges; const char *challenge; git_buf token = GIT_BUF_INIT; int error = 0; /* We've started a new request without creds; free the context. */ if (auth && !credentials) { free_auth_context(server); return 0; } /* We haven't authenticated, nor were we asked to. Nothing to do. */ if (!auth && !git_vector_length(challenges)) return 0; if (!auth) { challenge = init_auth_context(server, challenges, credentials); auth = server->auth_context; if (!challenge || !auth) { error = -1; goto done; } } else if (auth->set_challenge) { challenge = challenge_for_context(challenges, auth); } if (auth->set_challenge && challenge && (error = auth->set_challenge(auth, challenge)) < 0) goto done; if ((error = auth->next_token(&token, auth, credentials)) < 0) goto done; if (auth->is_complete && auth->is_complete(auth)) { /* * If we're done with an auth mechanism with connection affinity, * we don't need to send any more headers and can dispose the context. */ if (auth->connection_affinity) free_auth_context(server); } else if (!token.size) { git_error_set(GIT_ERROR_HTTP, "failed to respond to authentication challenge"); error = GIT_EAUTH; goto done; } if (token.size > 0) error = git_buf_printf(buf, "%s: %s\r\n", header_name, token.ptr); done: git_buf_dispose(&token); return error; } GIT_INLINE(int) apply_server_credentials( git_buf *buf, git_http_client *client, git_http_request *request) { return apply_credentials(buf, &client->server, "Authorization", request->credentials); } GIT_INLINE(int) apply_proxy_credentials( git_buf *buf, git_http_client *client, git_http_request *request) { return apply_credentials(buf, &client->proxy, "Proxy-Authorization", request->proxy_credentials); } static int puts_host_and_port(git_buf *buf, git_net_url *url, bool force_port) { bool ipv6 = git_net_url_is_ipv6(url); if (ipv6) git_buf_putc(buf, '['); git_buf_puts(buf, url->host); if (ipv6) git_buf_putc(buf, ']'); if (force_port || !git_net_url_is_default_port(url)) { git_buf_putc(buf, ':'); git_buf_puts(buf, url->port); } return git_buf_oom(buf) ? -1 : 0; } static int generate_connect_request( git_http_client *client, git_http_request *request) { git_buf *buf; int error; git_buf_clear(&client->request_msg); buf = &client->request_msg; git_buf_puts(buf, "CONNECT "); puts_host_and_port(buf, &client->server.url, true); git_buf_puts(buf, " HTTP/1.1\r\n"); git_buf_puts(buf, "User-Agent: "); git_http__user_agent(buf); git_buf_puts(buf, "\r\n"); git_buf_puts(buf, "Host: "); puts_host_and_port(buf, &client->server.url, true); git_buf_puts(buf, "\r\n"); if ((error = apply_proxy_credentials(buf, client, request) < 0)) return -1; git_buf_puts(buf, "\r\n"); return git_buf_oom(buf) ? -1 : 0; } static bool use_connect_proxy(git_http_client *client) { return client->proxy.url.host && !strcmp(client->server.url.scheme, "https"); } static int generate_request( git_http_client *client, git_http_request *request) { git_buf *buf; size_t i; int error; GIT_ASSERT_ARG(client); GIT_ASSERT_ARG(request); git_buf_clear(&client->request_msg); buf = &client->request_msg; /* GET|POST path HTTP/1.1 */ git_buf_puts(buf, name_for_method(request->method)); git_buf_putc(buf, ' '); if (request->proxy && strcmp(request->url->scheme, "https")) git_net_url_fmt(buf, request->url); else git_net_url_fmt_path(buf, request->url); git_buf_puts(buf, " HTTP/1.1\r\n"); git_buf_puts(buf, "User-Agent: "); git_http__user_agent(buf); git_buf_puts(buf, "\r\n"); git_buf_puts(buf, "Host: "); puts_host_and_port(buf, request->url, false); git_buf_puts(buf, "\r\n"); if (request->accept) git_buf_printf(buf, "Accept: %s\r\n", request->accept); else git_buf_puts(buf, "Accept: */*\r\n"); if (request->content_type) git_buf_printf(buf, "Content-Type: %s\r\n", request->content_type); if (request->chunked) git_buf_puts(buf, "Transfer-Encoding: chunked\r\n"); if (request->content_length > 0) git_buf_printf(buf, "Content-Length: %"PRIuZ "\r\n", request->content_length); if (request->expect_continue) git_buf_printf(buf, "Expect: 100-continue\r\n"); if ((error = apply_server_credentials(buf, client, request)) < 0 || (!use_connect_proxy(client) && (error = apply_proxy_credentials(buf, client, request)) < 0)) return error; if (request->custom_headers) { for (i = 0; i < request->custom_headers->count; i++) { const char *hdr = request->custom_headers->strings[i]; if (hdr) git_buf_printf(buf, "%s\r\n", hdr); } } git_buf_puts(buf, "\r\n"); if (git_buf_oom(buf)) return -1; return 0; } static int check_certificate( git_stream *stream, git_net_url *url, int is_valid, git_transport_certificate_check_cb cert_cb, void *cert_cb_payload) { git_cert *cert; git_error_state last_error = {0}; int error; if ((error = git_stream_certificate(&cert, stream)) < 0) return error; git_error_state_capture(&last_error, GIT_ECERTIFICATE); error = cert_cb(cert, is_valid, url->host, cert_cb_payload); if (error == GIT_PASSTHROUGH && !is_valid) return git_error_state_restore(&last_error); else if (error == GIT_PASSTHROUGH) error = 0; else if (error && !git_error_last()) git_error_set(GIT_ERROR_HTTP, "user rejected certificate for %s", url->host); git_error_state_free(&last_error); return error; } static int server_connect_stream( git_http_server *server, git_transport_certificate_check_cb cert_cb, void *cb_payload) { int error; GIT_ERROR_CHECK_VERSION(server->stream, GIT_STREAM_VERSION, "git_stream"); error = git_stream_connect(server->stream); if (error && error != GIT_ECERTIFICATE) return error; if (git_stream_is_encrypted(server->stream) && cert_cb != NULL) error = check_certificate(server->stream, &server->url, !error, cert_cb, cb_payload); return error; } static void reset_auth_connection(git_http_server *server) { /* * If we've authenticated and we're doing "normal" * authentication with a request affinity (Basic, Digest) * then we want to _keep_ our context, since authentication * survives even through non-keep-alive connections. If * we've authenticated and we're doing connection-based * authentication (NTLM, Negotiate) - indicated by the presence * of an `is_complete` callback - then we need to restart * authentication on a new connection. */ if (server->auth_context && server->auth_context->connection_affinity) free_auth_context(server); } /* * Updates the server data structure with the new URL; returns 1 if the server * has changed and we need to reconnect, returns 0 otherwise. */ GIT_INLINE(int) server_setup_from_url( git_http_server *server, git_net_url *url) { if (!server->url.scheme || strcmp(server->url.scheme, url->scheme) || !server->url.host || strcmp(server->url.host, url->host) || !server->url.port || strcmp(server->url.port, url->port)) { git__free(server->url.scheme); git__free(server->url.host); git__free(server->url.port); server->url.scheme = git__strdup(url->scheme); GIT_ERROR_CHECK_ALLOC(server->url.scheme); server->url.host = git__strdup(url->host); GIT_ERROR_CHECK_ALLOC(server->url.host); server->url.port = git__strdup(url->port); GIT_ERROR_CHECK_ALLOC(server->url.port); return 1; } return 0; } static void reset_parser(git_http_client *client) { http_parser_init(&client->parser, HTTP_RESPONSE); } static int setup_hosts( git_http_client *client, git_http_request *request) { int ret, diff = 0; GIT_ASSERT_ARG(client); GIT_ASSERT_ARG(request); GIT_ASSERT(request->url); if ((ret = server_setup_from_url(&client->server, request->url)) < 0) return ret; diff |= ret; if (request->proxy && (ret = server_setup_from_url(&client->proxy, request->proxy)) < 0) return ret; diff |= ret; if (diff) { free_auth_context(&client->server); free_auth_context(&client->proxy); client->connected = 0; } return 0; } GIT_INLINE(int) server_create_stream(git_http_server *server) { git_net_url *url = &server->url; if (strcasecmp(url->scheme, "https") == 0) return git_tls_stream_new(&server->stream, url->host, url->port); else if (strcasecmp(url->scheme, "http") == 0) return git_socket_stream_new(&server->stream, url->host, url->port); git_error_set(GIT_ERROR_HTTP, "unknown http scheme '%s'", url->scheme); return -1; } GIT_INLINE(void) save_early_response( git_http_client *client, git_http_response *response) { /* Buffer the response so we can return it in read_response */ client->state = HAS_EARLY_RESPONSE; memcpy(&client->early_response, response, sizeof(git_http_response)); memset(response, 0, sizeof(git_http_response)); } static int proxy_connect( git_http_client *client, git_http_request *request) { git_http_response response = {0}; int error; if (!client->proxy_connected || !client->keepalive) { git_trace(GIT_TRACE_DEBUG, "Connecting to proxy %s port %s", client->proxy.url.host, client->proxy.url.port); if ((error = server_create_stream(&client->proxy)) < 0 || (error = server_connect_stream(&client->proxy, client->opts.proxy_certificate_check_cb, client->opts.proxy_certificate_check_payload)) < 0) goto done; client->proxy_connected = 1; } client->current_server = PROXY; client->state = SENDING_REQUEST; if ((error = generate_connect_request(client, request)) < 0 || (error = client_write_request(client)) < 0) goto done; client->state = SENT_REQUEST; if ((error = git_http_client_read_response(&response, client)) < 0 || (error = git_http_client_skip_body(client)) < 0) goto done; GIT_ASSERT(client->state == DONE); if (response.status == GIT_HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED) { save_early_response(client, &response); error = GIT_RETRY; goto done; } else if (response.status != GIT_HTTP_STATUS_OK) { git_error_set(GIT_ERROR_HTTP, "proxy returned unexpected status: %d", response.status); error = -1; goto done; } reset_parser(client); client->state = NONE; done: git_http_response_dispose(&response); return error; } static int server_connect(git_http_client *client) { git_net_url *url = &client->server.url; git_transport_certificate_check_cb cert_cb; void *cert_payload; int error; client->current_server = SERVER; if (client->proxy.stream) error = git_tls_stream_wrap(&client->server.stream, client->proxy.stream, url->host); else error = server_create_stream(&client->server); if (error < 0) goto done; cert_cb = client->opts.server_certificate_check_cb; cert_payload = client->opts.server_certificate_check_payload; error = server_connect_stream(&client->server, cert_cb, cert_payload); done: return error; } GIT_INLINE(void) close_stream(git_http_server *server) { if (server->stream) { git_stream_close(server->stream); git_stream_free(server->stream); server->stream = NULL; } } static int http_client_connect( git_http_client *client, git_http_request *request) { bool use_proxy = false; int error; if ((error = setup_hosts(client, request)) < 0) goto on_error; /* We're connected to our destination server; no need to reconnect */ if (client->connected && client->keepalive && (client->state == NONE || client->state == DONE)) return 0; client->connected = 0; client->request_count = 0; close_stream(&client->server); reset_auth_connection(&client->server); reset_parser(client); /* Reconnect to the proxy if necessary. */ use_proxy = use_connect_proxy(client); if (use_proxy) { if (!client->proxy_connected || !client->keepalive || (client->state != NONE && client->state != DONE)) { close_stream(&client->proxy); reset_auth_connection(&client->proxy); client->proxy_connected = 0; } if ((error = proxy_connect(client, request)) < 0) goto on_error; } git_trace(GIT_TRACE_DEBUG, "Connecting to remote %s port %s", client->server.url.host, client->server.url.port); if ((error = server_connect(client)) < 0) goto on_error; client->connected = 1; return error; on_error: if (error != GIT_RETRY) close_stream(&client->proxy); close_stream(&client->server); return error; } GIT_INLINE(int) client_read(git_http_client *client) { http_parser_context *parser_context = client->parser.data; git_stream *stream; char *buf = client->read_buf.ptr + client->read_buf.size; size_t max_len; ssize_t read_len; stream = client->current_server == PROXY ? client->proxy.stream : client->server.stream; /* * We use a git_buf for convenience, but statically allocate it and * don't resize. Limit our consumption to INT_MAX since calling * functions use an int return type to return number of bytes read. */ max_len = client->read_buf.asize - client->read_buf.size; max_len = min(max_len, INT_MAX); if (parser_context->output_size) max_len = min(max_len, parser_context->output_size); if (max_len == 0) { git_error_set(GIT_ERROR_HTTP, "no room in output buffer"); return -1; } read_len = git_stream_read(stream, buf, max_len); if (read_len >= 0) { client->read_buf.size += read_len; git_trace(GIT_TRACE_TRACE, "Received:\n%.*s", (int)read_len, buf); } return (int)read_len; } static bool parser_settings_initialized; static http_parser_settings parser_settings; GIT_INLINE(http_parser_settings *) http_client_parser_settings(void) { if (!parser_settings_initialized) { parser_settings.on_header_field = on_header_field; parser_settings.on_header_value = on_header_value; parser_settings.on_headers_complete = on_headers_complete; parser_settings.on_body = on_body; parser_settings.on_message_complete = on_message_complete; parser_settings_initialized = true; } return &parser_settings; } GIT_INLINE(int) client_read_and_parse(git_http_client *client) { http_parser *parser = &client->parser; http_parser_context *ctx = (http_parser_context *) parser->data; unsigned char http_errno; int read_len; size_t parsed_len; /* * If we have data in our read buffer, that means we stopped early * when parsing headers. Use the data in the read buffer instead of * reading more from the socket. */ if (!client->read_buf.size && (read_len = client_read(client)) < 0) return read_len; parsed_len = http_parser_execute(parser, http_client_parser_settings(), client->read_buf.ptr, client->read_buf.size); http_errno = client->parser.http_errno; if (parsed_len > INT_MAX) { git_error_set(GIT_ERROR_HTTP, "unexpectedly large parse"); return -1; } if (ctx->parse_status == PARSE_STATUS_ERROR) { client->connected = 0; return ctx->error ? ctx->error : -1; } /* * If we finished reading the headers or body, we paused parsing. * Otherwise the parser will start filling the body, or even parse * a new response if the server pipelined us multiple responses. * (This can happen in response to an expect/continue request, * where the server gives you a 100 and 200 simultaneously.) */ if (http_errno == HPE_PAUSED) { /* * http-parser has a "feature" where it will not deliver the * final byte when paused in a callback. Consume that byte. * https://github.com/nodejs/http-parser/issues/97 */ GIT_ASSERT(client->read_buf.size > parsed_len); http_parser_pause(parser, 0); parsed_len += http_parser_execute(parser, http_client_parser_settings(), client->read_buf.ptr + parsed_len, 1); } /* Most failures will be reported in http_errno */ else if (parser->http_errno != HPE_OK) { git_error_set(GIT_ERROR_HTTP, "http parser error: %s", http_errno_description(http_errno)); return -1; } /* Otherwise we should have consumed the entire buffer. */ else if (parsed_len != client->read_buf.size) { git_error_set(GIT_ERROR_HTTP, "http parser did not consume entire buffer: %s", http_errno_description(http_errno)); return -1; } /* recv returned 0, the server hung up on us */ else if (!parsed_len) { git_error_set(GIT_ERROR_HTTP, "unexpected EOF"); return -1; } git_buf_consume_bytes(&client->read_buf, parsed_len); return (int)parsed_len; } /* * See if we've consumed the entire response body. If the client was * reading the body but did not consume it entirely, it's possible that * they knew that the stream had finished (in a git response, seeing a * final flush) and stopped reading. But if the response was chunked, * we may have not consumed the final chunk marker. Consume it to * ensure that we don't have it waiting in our socket. If there's * more than just a chunk marker, close the connection. */ static void complete_response_body(git_http_client *client) { http_parser_context parser_context = {0}; /* If we're not keeping alive, don't bother. */ if (!client->keepalive) { client->connected = 0; goto done; } parser_context.client = client; client->parser.data = &parser_context; /* If there was an error, just close the connection. */ if (client_read_and_parse(client) < 0 || parser_context.error != HPE_OK || (parser_context.parse_status != PARSE_STATUS_OK && parser_context.parse_status != PARSE_STATUS_NO_OUTPUT)) { git_error_clear(); client->connected = 0; } done: git_buf_clear(&client->read_buf); } int git_http_client_send_request( git_http_client *client, git_http_request *request) { git_http_response response = {0}; int error = -1; GIT_ASSERT_ARG(client); GIT_ASSERT_ARG(request); /* If the client did not finish reading, clean up the stream. */ if (client->state == READING_BODY) complete_response_body(client); /* If we're waiting for proxy auth, don't sending more requests. */ if (client->state == HAS_EARLY_RESPONSE) return 0; if (git_trace_level() >= GIT_TRACE_DEBUG) { git_buf url = GIT_BUF_INIT; git_net_url_fmt(&url, request->url); git_trace(GIT_TRACE_DEBUG, "Sending %s request to %s", name_for_method(request->method), url.ptr ? url.ptr : "<invalid>"); git_buf_dispose(&url); } if ((error = http_client_connect(client, request)) < 0 || (error = generate_request(client, request)) < 0 || (error = client_write_request(client)) < 0) goto done; client->state = SENT_REQUEST; if (request->expect_continue) { if ((error = git_http_client_read_response(&response, client)) < 0 || (error = git_http_client_skip_body(client)) < 0) goto done; error = 0; if (response.status != GIT_HTTP_STATUS_CONTINUE) { save_early_response(client, &response); goto done; } } if (request->content_length || request->chunked) { client->state = SENDING_BODY; client->request_body_len = request->content_length; client->request_body_remain = request->content_length; client->request_chunked = request->chunked; } reset_parser(client); done: if (error == GIT_RETRY) error = 0; git_http_response_dispose(&response); return error; } bool git_http_client_has_response(git_http_client *client) { return (client->state == HAS_EARLY_RESPONSE || client->state > SENT_REQUEST); } int git_http_client_send_body( git_http_client *client, const char *buffer, size_t buffer_len) { git_http_server *server; git_buf hdr = GIT_BUF_INIT; int error; GIT_ASSERT_ARG(client); /* If we're waiting for proxy auth, don't sending more requests. */ if (client->state == HAS_EARLY_RESPONSE) return 0; if (client->state != SENDING_BODY) { git_error_set(GIT_ERROR_HTTP, "client is in invalid state"); return -1; } if (!buffer_len) return 0; server = &client->server; if (client->request_body_len) { GIT_ASSERT(buffer_len <= client->request_body_remain); if ((error = stream_write(server, buffer, buffer_len)) < 0) goto done; client->request_body_remain -= buffer_len; } else { if ((error = git_buf_printf(&hdr, "%" PRIxZ "\r\n", buffer_len)) < 0 || (error = stream_write(server, hdr.ptr, hdr.size)) < 0 || (error = stream_write(server, buffer, buffer_len)) < 0 || (error = stream_write(server, "\r\n", 2)) < 0) goto done; } done: git_buf_dispose(&hdr); return error; } static int complete_request(git_http_client *client) { int error = 0; GIT_ASSERT_ARG(client); GIT_ASSERT(client->state == SENDING_BODY); if (client->request_body_len && client->request_body_remain) { git_error_set(GIT_ERROR_HTTP, "truncated write"); error = -1; } else if (client->request_chunked) { error = stream_write(&client->server, "0\r\n\r\n", 5); } client->state = SENT_REQUEST; return error; } int git_http_client_read_response( git_http_response *response, git_http_client *client) { http_parser_context parser_context = {0}; int error; GIT_ASSERT_ARG(response); GIT_ASSERT_ARG(client); if (client->state == SENDING_BODY) { if ((error = complete_request(client)) < 0) goto done; } if (client->state == HAS_EARLY_RESPONSE) { memcpy(response, &client->early_response, sizeof(git_http_response)); memset(&client->early_response, 0, sizeof(git_http_response)); client->state = DONE; return 0; } if (client->state != SENT_REQUEST) { git_error_set(GIT_ERROR_HTTP, "client is in invalid state"); error = -1; goto done; } git_http_response_dispose(response); if (client->current_server == PROXY) { git_vector_free_deep(&client->proxy.auth_challenges); } else if(client->current_server == SERVER) { git_vector_free_deep(&client->server.auth_challenges); } client->state = READING_RESPONSE; client->keepalive = 0; client->parser.data = &parser_context; parser_context.client = client; parser_context.response = response; while (client->state == READING_RESPONSE) { if ((error = client_read_and_parse(client)) < 0) goto done; } GIT_ASSERT(client->state == READING_BODY || client->state == DONE); done: git_buf_dispose(&parser_context.parse_header_name); git_buf_dispose(&parser_context.parse_header_value); return error; } int git_http_client_read_body( git_http_client *client, char *buffer, size_t buffer_size) { http_parser_context parser_context = {0}; int error = 0; if (client->state == DONE) return 0; if (client->state != READING_BODY) { git_error_set(GIT_ERROR_HTTP, "client is in invalid state"); return -1; } /* * Now we'll read from the socket and http_parser will pipeline the * data directly to the client. */ parser_context.client = client; parser_context.output_buf = buffer; parser_context.output_size = buffer_size; client->parser.data = &parser_context; /* * Clients expect to get a non-zero amount of data from us, * so we either block until we have data to return, until we * hit EOF or there's an error. Do this in a loop, since we * may end up reading only some stream metadata (like chunk * information). */ while (!parser_context.output_written) { error = client_read_and_parse(client); if (error <= 0) goto done; if (client->state == DONE) break; } GIT_ASSERT(parser_context.output_written <= INT_MAX); error = (int)parser_context.output_written; done: if (error < 0) client->connected = 0; return error; } int git_http_client_skip_body(git_http_client *client) { http_parser_context parser_context = {0}; int error; if (client->state == DONE) return 0; if (client->state != READING_BODY) { git_error_set(GIT_ERROR_HTTP, "client is in invalid state"); return -1; } parser_context.client = client; client->parser.data = &parser_context; do { error = client_read_and_parse(client); if (parser_context.error != HPE_OK || (parser_context.parse_status != PARSE_STATUS_OK && parser_context.parse_status != PARSE_STATUS_NO_OUTPUT)) { git_error_set(GIT_ERROR_HTTP, "unexpected data handled in callback"); error = -1; } } while (error >= 0 && client->state != DONE); if (error < 0) client->connected = 0; return error; } /* * Create an http_client capable of communicating with the given remote * host. */ int git_http_client_new( git_http_client **out, git_http_client_options *opts) { git_http_client *client; GIT_ASSERT_ARG(out); client = git__calloc(1, sizeof(git_http_client)); GIT_ERROR_CHECK_ALLOC(client); git_buf_init(&client->read_buf, GIT_READ_BUFFER_SIZE); GIT_ERROR_CHECK_ALLOC(client->read_buf.ptr); if (opts) memcpy(&client->opts, opts, sizeof(git_http_client_options)); *out = client; return 0; } GIT_INLINE(void) http_server_close(git_http_server *server) { if (server->stream) { git_stream_close(server->stream); git_stream_free(server->stream); server->stream = NULL; } git_net_url_dispose(&server->url); git_vector_free_deep(&server->auth_challenges); free_auth_context(server); } static void http_client_close(git_http_client *client) { http_server_close(&client->server); http_server_close(&client->proxy); git_buf_dispose(&client->request_msg); client->state = 0; client->request_count = 0; client->connected = 0; client->keepalive = 0; } void git_http_client_free(git_http_client *client) { if (!client) return; http_client_close(client); git_buf_dispose(&client->read_buf); git__free(client); }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/transports/smart.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_transports_smart_h__ #define INCLUDE_transports_smart_h__ #include "common.h" #include "git2.h" #include "vector.h" #include "netops.h" #include "buffer.h" #include "push.h" #include "git2/sys/transport.h" #define GIT_SIDE_BAND_DATA 1 #define GIT_SIDE_BAND_PROGRESS 2 #define GIT_SIDE_BAND_ERROR 3 #define GIT_CAP_OFS_DELTA "ofs-delta" #define GIT_CAP_MULTI_ACK "multi_ack" #define GIT_CAP_MULTI_ACK_DETAILED "multi_ack_detailed" #define GIT_CAP_SIDE_BAND "side-band" #define GIT_CAP_SIDE_BAND_64K "side-band-64k" #define GIT_CAP_INCLUDE_TAG "include-tag" #define GIT_CAP_DELETE_REFS "delete-refs" #define GIT_CAP_REPORT_STATUS "report-status" #define GIT_CAP_THIN_PACK "thin-pack" #define GIT_CAP_SYMREF "symref" extern bool git_smart__ofs_delta_enabled; typedef enum { GIT_PKT_CMD, GIT_PKT_FLUSH, GIT_PKT_REF, GIT_PKT_HAVE, GIT_PKT_ACK, GIT_PKT_NAK, GIT_PKT_COMMENT, GIT_PKT_ERR, GIT_PKT_DATA, GIT_PKT_PROGRESS, GIT_PKT_OK, GIT_PKT_NG, GIT_PKT_UNPACK, } git_pkt_type; /* Used for multi_ack and multi_ack_detailed */ enum git_ack_status { GIT_ACK_NONE, GIT_ACK_CONTINUE, GIT_ACK_COMMON, GIT_ACK_READY }; /* This would be a flush pkt */ typedef struct { git_pkt_type type; } git_pkt; struct git_pkt_cmd { git_pkt_type type; char *cmd; char *path; char *host; }; /* This is a pkt-line with some info in it */ typedef struct { git_pkt_type type; git_remote_head head; char *capabilities; } git_pkt_ref; /* Useful later */ typedef struct { git_pkt_type type; git_oid oid; enum git_ack_status status; } git_pkt_ack; typedef struct { git_pkt_type type; char comment[GIT_FLEX_ARRAY]; } git_pkt_comment; typedef struct { git_pkt_type type; size_t len; char data[GIT_FLEX_ARRAY]; } git_pkt_data; typedef git_pkt_data git_pkt_progress; typedef struct { git_pkt_type type; size_t len; char error[GIT_FLEX_ARRAY]; } git_pkt_err; typedef struct { git_pkt_type type; char *ref; } git_pkt_ok; typedef struct { git_pkt_type type; char *ref; char *msg; } git_pkt_ng; typedef struct { git_pkt_type type; int unpack_ok; } git_pkt_unpack; typedef struct transport_smart_caps { int common:1, ofs_delta:1, multi_ack: 1, multi_ack_detailed: 1, side_band:1, side_band_64k:1, include_tag:1, delete_refs:1, report_status:1, thin_pack:1; } transport_smart_caps; typedef int (*packetsize_cb)(size_t received, void *payload); typedef struct { git_transport parent; git_remote *owner; char *url; git_credential_acquire_cb cred_acquire_cb; void *cred_acquire_payload; git_proxy_options proxy; int direction; int flags; git_transport_message_cb progress_cb; git_transport_message_cb error_cb; git_transport_certificate_check_cb certificate_check_cb; void *message_cb_payload; git_strarray custom_headers; git_smart_subtransport *wrapped; git_smart_subtransport_stream *current_stream; transport_smart_caps caps; git_vector refs; git_vector heads; git_vector common; git_atomic32 cancelled; packetsize_cb packetsize_cb; void *packetsize_payload; unsigned rpc : 1, have_refs : 1, connected : 1; gitno_buffer buffer; char buffer_data[65536]; } transport_smart; /* smart_protocol.c */ int git_smart__store_refs(transport_smart *t, int flushes); int git_smart__detect_caps(git_pkt_ref *pkt, transport_smart_caps *caps, git_vector *symrefs); int git_smart__push(git_transport *transport, git_push *push, const git_remote_callbacks *cbs); int git_smart__negotiate_fetch( git_transport *transport, git_repository *repo, const git_remote_head * const *refs, size_t count); int git_smart__download_pack( git_transport *transport, git_repository *repo, git_indexer_progress *stats, git_indexer_progress_cb progress_cb, void *progress_payload); /* smart.c */ int git_smart__negotiation_step(git_transport *transport, void *data, size_t len); int git_smart__get_push_stream(transport_smart *t, git_smart_subtransport_stream **out); int git_smart__update_heads(transport_smart *t, git_vector *symrefs); /* smart_pkt.c */ int git_pkt_parse_line(git_pkt **head, const char **endptr, const char *line, size_t linelen); int git_pkt_buffer_flush(git_buf *buf); int git_pkt_send_flush(GIT_SOCKET s); int git_pkt_buffer_done(git_buf *buf); int git_pkt_buffer_wants(const git_remote_head * const *refs, size_t count, transport_smart_caps *caps, git_buf *buf); int git_pkt_buffer_have(git_oid *oid, git_buf *buf); void git_pkt_free(git_pkt *pkt); #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/transports/http.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_transports_http_h__ #define INCLUDE_transports_http_h__ #include "buffer.h" #include "settings.h" #include "httpclient.h" #define GIT_HTTP_REPLAY_MAX 15 extern bool git_http__expect_continue; GIT_INLINE(int) git_http__user_agent(git_buf *buf) { const char *ua = git_libgit2__user_agent(); if (!ua) ua = "libgit2 " LIBGIT2_VERSION; return git_buf_printf(buf, "git/2.0 (%s)", ua); } #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/streams/tls.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_streams_tls_h__ #define INCLUDE_streams_tls_h__ #include "common.h" #include "git2/sys/stream.h" /** * Create a TLS stream with the most appropriate backend available for * the current platform, whether that's SecureTransport on macOS, * OpenSSL or mbedTLS on other Unixes, or something else entirely. */ extern int git_tls_stream_new(git_stream **out, const char *host, const char *port); /** * Create a TLS stream on top of an existing insecure stream, using * the most appropriate backend available for the current platform. * * This allows us to create a CONNECT stream on top of a proxy; * using SecureTransport on macOS, OpenSSL or mbedTLS on other * Unixes, or something else entirely. */ extern int git_tls_stream_wrap(git_stream **out, git_stream *in, const char *host); #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/streams/tls.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "git2/errors.h" #include "common.h" #include "streams/registry.h" #include "streams/tls.h" #include "streams/mbedtls.h" #include "streams/openssl.h" #include "streams/stransport.h" int git_tls_stream_new(git_stream **out, const char *host, const char *port) { int (*init)(git_stream **, const char *, const char *) = NULL; git_stream_registration custom = {0}; int error; GIT_ASSERT_ARG(out); GIT_ASSERT_ARG(host); GIT_ASSERT_ARG(port); if ((error = git_stream_registry_lookup(&custom, GIT_STREAM_TLS)) == 0) { init = custom.init; } else if (error == GIT_ENOTFOUND) { #ifdef GIT_SECURE_TRANSPORT init = git_stransport_stream_new; #elif defined(GIT_OPENSSL) init = git_openssl_stream_new; #elif defined(GIT_MBEDTLS) init = git_mbedtls_stream_new; #endif } else { return error; } if (!init) { git_error_set(GIT_ERROR_SSL, "there is no TLS stream available"); return -1; } return init(out, host, port); } int git_tls_stream_wrap(git_stream **out, git_stream *in, const char *host) { int (*wrap)(git_stream **, git_stream *, const char *) = NULL; git_stream_registration custom = {0}; GIT_ASSERT_ARG(out); GIT_ASSERT_ARG(in); if (git_stream_registry_lookup(&custom, GIT_STREAM_TLS) == 0) { wrap = custom.wrap; } else { #ifdef GIT_SECURE_TRANSPORT wrap = git_stransport_stream_wrap; #elif defined(GIT_OPENSSL) wrap = git_openssl_stream_wrap; #elif defined(GIT_MBEDTLS) wrap = git_mbedtls_stream_wrap; #endif } if (!wrap) { git_error_set(GIT_ERROR_SSL, "there is no TLS stream available"); return -1; } return wrap(out, in, host); }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/streams/socket.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_streams_socket_h__ #define INCLUDE_streams_socket_h__ #include "common.h" #include "netops.h" typedef struct { git_stream parent; char *host; char *port; GIT_SOCKET s; } git_socket_stream; extern int git_socket_stream_new(git_stream **out, const char *host, const char *port); #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/streams/openssl.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_streams_openssl_h__ #define INCLUDE_streams_openssl_h__ #include "common.h" #include "streams/openssl_legacy.h" #include "streams/openssl_dynamic.h" #include "git2/sys/stream.h" extern int git_openssl_stream_global_init(void); #if defined(GIT_OPENSSL) && !defined(GIT_OPENSSL_DYNAMIC) # include <openssl/ssl.h> # include <openssl/err.h> # include <openssl/x509v3.h> # include <openssl/bio.h> # endif #ifdef GIT_OPENSSL extern int git_openssl__set_cert_location(const char *file, const char *path); extern int git_openssl_stream_new(git_stream **out, const char *host, const char *port); extern int git_openssl_stream_wrap(git_stream **out, git_stream *in, const char *host); #endif #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/streams/stransport.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_streams_stransport_h__ #define INCLUDE_streams_stransport_h__ #include "common.h" #include "git2/sys/stream.h" #ifdef GIT_SECURE_TRANSPORT extern int git_stransport_stream_new(git_stream **out, const char *host, const char *port); extern int git_stransport_stream_wrap(git_stream **out, git_stream *in, const char *host); #endif #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/streams/socket.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "streams/socket.h" #include "posix.h" #include "netops.h" #include "registry.h" #include "stream.h" #ifndef _WIN32 # include <sys/types.h> # include <sys/socket.h> # include <sys/select.h> # include <sys/time.h> # include <netdb.h> # include <netinet/in.h> # include <arpa/inet.h> #else # include <winsock2.h> # include <ws2tcpip.h> # ifdef _MSC_VER # pragma comment(lib, "ws2_32") # endif #endif #ifdef GIT_WIN32 static void net_set_error(const char *str) { int error = WSAGetLastError(); char * win32_error = git_win32_get_error_message(error); if (win32_error) { git_error_set(GIT_ERROR_NET, "%s: %s", str, win32_error); git__free(win32_error); } else { git_error_set(GIT_ERROR_NET, "%s", str); } } #else static void net_set_error(const char *str) { git_error_set(GIT_ERROR_NET, "%s: %s", str, strerror(errno)); } #endif static int close_socket(GIT_SOCKET s) { if (s == INVALID_SOCKET) return 0; #ifdef GIT_WIN32 if (SOCKET_ERROR == closesocket(s)) return -1; if (0 != WSACleanup()) { git_error_set(GIT_ERROR_OS, "winsock cleanup failed"); return -1; } return 0; #else return close(s); #endif } static int socket_connect(git_stream *stream) { struct addrinfo *info = NULL, *p; struct addrinfo hints; git_socket_stream *st = (git_socket_stream *) stream; GIT_SOCKET s = INVALID_SOCKET; int ret; #ifdef GIT_WIN32 /* on win32, the WSA context needs to be initialized * before any socket calls can be performed */ WSADATA wsd; if (WSAStartup(MAKEWORD(2,2), &wsd) != 0) { git_error_set(GIT_ERROR_OS, "winsock init failed"); return -1; } if (LOBYTE(wsd.wVersion) != 2 || HIBYTE(wsd.wVersion) != 2) { WSACleanup(); git_error_set(GIT_ERROR_OS, "winsock init failed"); return -1; } #endif memset(&hints, 0x0, sizeof(struct addrinfo)); hints.ai_socktype = SOCK_STREAM; hints.ai_family = AF_UNSPEC; if ((ret = p_getaddrinfo(st->host, st->port, &hints, &info)) != 0) { git_error_set(GIT_ERROR_NET, "failed to resolve address for %s: %s", st->host, p_gai_strerror(ret)); return -1; } for (p = info; p != NULL; p = p->ai_next) { s = socket(p->ai_family, p->ai_socktype | SOCK_CLOEXEC, p->ai_protocol); if (s == INVALID_SOCKET) continue; if (connect(s, p->ai_addr, (socklen_t)p->ai_addrlen) == 0) break; /* If we can't connect, try the next one */ close_socket(s); s = INVALID_SOCKET; } /* Oops, we couldn't connect to any address */ if (s == INVALID_SOCKET && p == NULL) { git_error_set(GIT_ERROR_OS, "failed to connect to %s", st->host); p_freeaddrinfo(info); return -1; } st->s = s; p_freeaddrinfo(info); return 0; } static ssize_t socket_write(git_stream *stream, const char *data, size_t len, int flags) { git_socket_stream *st = (git_socket_stream *) stream; ssize_t written; errno = 0; if ((written = p_send(st->s, data, len, flags)) < 0) { net_set_error("error sending data"); return -1; } return written; } static ssize_t socket_read(git_stream *stream, void *data, size_t len) { ssize_t ret; git_socket_stream *st = (git_socket_stream *) stream; if ((ret = p_recv(st->s, data, len, 0)) < 0) net_set_error("error receiving socket data"); return ret; } static int socket_close(git_stream *stream) { git_socket_stream *st = (git_socket_stream *) stream; int error; error = close_socket(st->s); st->s = INVALID_SOCKET; return error; } static void socket_free(git_stream *stream) { git_socket_stream *st = (git_socket_stream *) stream; git__free(st->host); git__free(st->port); git__free(st); } static int default_socket_stream_new( git_stream **out, const char *host, const char *port) { git_socket_stream *st; GIT_ASSERT_ARG(out); GIT_ASSERT_ARG(host); GIT_ASSERT_ARG(port); st = git__calloc(1, sizeof(git_socket_stream)); GIT_ERROR_CHECK_ALLOC(st); st->host = git__strdup(host); GIT_ERROR_CHECK_ALLOC(st->host); if (port) { st->port = git__strdup(port); GIT_ERROR_CHECK_ALLOC(st->port); } st->parent.version = GIT_STREAM_VERSION; st->parent.connect = socket_connect; st->parent.write = socket_write; st->parent.read = socket_read; st->parent.close = socket_close; st->parent.free = socket_free; st->s = INVALID_SOCKET; *out = (git_stream *) st; return 0; } int git_socket_stream_new( git_stream **out, const char *host, const char *port) { int (*init)(git_stream **, const char *, const char *) = NULL; git_stream_registration custom = {0}; int error; GIT_ASSERT_ARG(out); GIT_ASSERT_ARG(host); GIT_ASSERT_ARG(port); if ((error = git_stream_registry_lookup(&custom, GIT_STREAM_STANDARD)) == 0) init = custom.init; else if (error == GIT_ENOTFOUND) init = default_socket_stream_new; else return error; if (!init) { git_error_set(GIT_ERROR_NET, "there is no socket stream available"); return -1; } return init(out, host, port); }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/streams/openssl_legacy.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "streams/openssl.h" #include "streams/openssl_legacy.h" #include "runtime.h" #include "git2/sys/openssl.h" #if defined(GIT_OPENSSL) && !defined(GIT_OPENSSL_DYNAMIC) # include <openssl/ssl.h> # include <openssl/err.h> # include <openssl/x509v3.h> # include <openssl/bio.h> #endif #if defined(GIT_OPENSSL_LEGACY) || defined(GIT_OPENSSL_DYNAMIC) /* * OpenSSL 1.1 made BIO opaque so we have to use functions to interact with it * which do not exist in previous versions. We define these inline functions so * we can program against the interface instead of littering the implementation * with ifdefs. We do the same for OPENSSL_init_ssl. */ int OPENSSL_init_ssl__legacy(uint64_t opts, const void *settings) { GIT_UNUSED(opts); GIT_UNUSED(settings); SSL_load_error_strings(); SSL_library_init(); return 0; } BIO_METHOD *BIO_meth_new__legacy(int type, const char *name) { BIO_METHOD *meth = git__calloc(1, sizeof(BIO_METHOD)); if (!meth) { return NULL; } meth->type = type; meth->name = name; return meth; } void BIO_meth_free__legacy(BIO_METHOD *biom) { git__free(biom); } int BIO_meth_set_write__legacy(BIO_METHOD *biom, int (*write) (BIO *, const char *, int)) { biom->bwrite = write; return 1; } int BIO_meth_set_read__legacy(BIO_METHOD *biom, int (*read) (BIO *, char *, int)) { biom->bread = read; return 1; } int BIO_meth_set_puts__legacy(BIO_METHOD *biom, int (*puts) (BIO *, const char *)) { biom->bputs = puts; return 1; } int BIO_meth_set_gets__legacy(BIO_METHOD *biom, int (*gets) (BIO *, char *, int)) { biom->bgets = gets; return 1; } int BIO_meth_set_ctrl__legacy(BIO_METHOD *biom, long (*ctrl) (BIO *, int, long, void *)) { biom->ctrl = ctrl; return 1; } int BIO_meth_set_create__legacy(BIO_METHOD *biom, int (*create) (BIO *)) { biom->create = create; return 1; } int BIO_meth_set_destroy__legacy(BIO_METHOD *biom, int (*destroy) (BIO *)) { biom->destroy = destroy; return 1; } int BIO_get_new_index__legacy(void) { /* This exists as of 1.1 so before we'd just have 0 */ return 0; } void BIO_set_init__legacy(BIO *b, int init) { b->init = init; } void BIO_set_data__legacy(BIO *a, void *ptr) { a->ptr = ptr; } void *BIO_get_data__legacy(BIO *a) { return a->ptr; } const unsigned char *ASN1_STRING_get0_data__legacy(const ASN1_STRING *x) { return ASN1_STRING_data((ASN1_STRING *)x); } long SSL_CTX_set_options__legacy(SSL_CTX *ctx, long op) { return SSL_CTX_ctrl(ctx, SSL_CTRL_OPTIONS, op, NULL); } # if defined(GIT_THREADS) static git_mutex *openssl_locks; static void openssl_locking_function(int mode, int n, const char *file, int line) { int lock; GIT_UNUSED(file); GIT_UNUSED(line); lock = mode & CRYPTO_LOCK; if (lock) (void)git_mutex_lock(&openssl_locks[n]); else git_mutex_unlock(&openssl_locks[n]); } static void shutdown_ssl_locking(void) { int num_locks, i; num_locks = CRYPTO_num_locks(); CRYPTO_set_locking_callback(NULL); for (i = 0; i < num_locks; ++i) git_mutex_free(&openssl_locks[i]); git__free(openssl_locks); } static void threadid_cb(CRYPTO_THREADID *threadid) { GIT_UNUSED(threadid); CRYPTO_THREADID_set_numeric(threadid, git_thread_currentid()); } int git_openssl_set_locking(void) { int num_locks, i; #ifndef GIT_THREADS git_error_set(GIT_ERROR_THREAD, "libgit2 was not built with threads"); return -1; #endif #ifdef GIT_OPENSSL_DYNAMIC /* * This function is required on legacy versions of OpenSSL; when building * with dynamically-loaded OpenSSL, we detect whether we loaded it or not. */ if (!CRYPTO_set_locking_callback) return 0; #endif CRYPTO_THREADID_set_callback(threadid_cb); num_locks = CRYPTO_num_locks(); openssl_locks = git__calloc(num_locks, sizeof(git_mutex)); GIT_ERROR_CHECK_ALLOC(openssl_locks); for (i = 0; i < num_locks; i++) { if (git_mutex_init(&openssl_locks[i]) != 0) { git_error_set(GIT_ERROR_SSL, "failed to initialize openssl locks"); return -1; } } CRYPTO_set_locking_callback(openssl_locking_function); return git_runtime_shutdown_register(shutdown_ssl_locking); } #endif /* GIT_THREADS */ #endif /* GIT_OPENSSL_LEGACY || GIT_OPENSSL_DYNAMIC */
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/streams/openssl.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "streams/openssl.h" #include "streams/openssl_legacy.h" #include "streams/openssl_dynamic.h" #ifdef GIT_OPENSSL #include <ctype.h> #include "common.h" #include "runtime.h" #include "settings.h" #include "posix.h" #include "stream.h" #include "streams/socket.h" #include "netops.h" #include "git2/transport.h" #include "git2/sys/openssl.h" #ifndef GIT_WIN32 # include <sys/types.h> # include <sys/socket.h> # include <netinet/in.h> #endif #ifndef GIT_OPENSSL_DYNAMIC # include <openssl/ssl.h> # include <openssl/err.h> # include <openssl/x509v3.h> # include <openssl/bio.h> #endif SSL_CTX *git__ssl_ctx; #define GIT_SSL_DEFAULT_CIPHERS "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-DSS-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:DHE-DSS-AES128-SHA256:DHE-DSS-AES256-SHA256:DHE-DSS-AES128-SHA:DHE-DSS-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA" static BIO_METHOD *git_stream_bio_method; static int init_bio_method(void); /** * This function aims to clean-up the SSL context which * we allocated. */ static void shutdown_ssl(void) { if (git_stream_bio_method) { BIO_meth_free(git_stream_bio_method); git_stream_bio_method = NULL; } if (git__ssl_ctx) { SSL_CTX_free(git__ssl_ctx); git__ssl_ctx = NULL; } } #ifdef VALGRIND # if !defined(GIT_OPENSSL_LEGACY) && !defined(GIT_OPENSSL_DYNAMIC) static void *git_openssl_malloc(size_t bytes, const char *file, int line) { GIT_UNUSED(file); GIT_UNUSED(line); return git__calloc(1, bytes); } static void *git_openssl_realloc(void *mem, size_t size, const char *file, int line) { GIT_UNUSED(file); GIT_UNUSED(line); return git__realloc(mem, size); } static void git_openssl_free(void *mem, const char *file, int line) { GIT_UNUSED(file); GIT_UNUSED(line); git__free(mem); } # else /* !GIT_OPENSSL_LEGACY && !GIT_OPENSSL_DYNAMIC */ static void *git_openssl_malloc(size_t bytes) { return git__calloc(1, bytes); } static void *git_openssl_realloc(void *mem, size_t size) { return git__realloc(mem, size); } static void git_openssl_free(void *mem) { git__free(mem); } # endif /* !GIT_OPENSSL_LEGACY && !GIT_OPENSSL_DYNAMIC */ #endif /* VALGRIND */ static int openssl_init(void) { long ssl_opts = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3; const char *ciphers = git_libgit2__ssl_ciphers(); #ifdef VALGRIND static bool allocators_initialized = false; #endif /* Older OpenSSL and MacOS OpenSSL doesn't have this */ #ifdef SSL_OP_NO_COMPRESSION ssl_opts |= SSL_OP_NO_COMPRESSION; #endif #ifdef VALGRIND /* * Swap in our own allocator functions that initialize * allocated memory to avoid spurious valgrind warnings. * Don't error on failure; many builds of OpenSSL do not * allow you to set these functions. */ if (!allocators_initialized) { CRYPTO_set_mem_functions(git_openssl_malloc, git_openssl_realloc, git_openssl_free); allocators_initialized = true; } #endif OPENSSL_init_ssl(0, NULL); /* * Load SSLv{2,3} and TLSv1 so that we can talk with servers * which use the SSL hellos, which are often used for * compatibility. We then disable SSL so we only allow OpenSSL * to speak TLSv1 to perform the encryption itself. */ if (!(git__ssl_ctx = SSL_CTX_new(SSLv23_method()))) goto error; SSL_CTX_set_options(git__ssl_ctx, ssl_opts); SSL_CTX_set_mode(git__ssl_ctx, SSL_MODE_AUTO_RETRY); SSL_CTX_set_verify(git__ssl_ctx, SSL_VERIFY_NONE, NULL); if (!SSL_CTX_set_default_verify_paths(git__ssl_ctx)) goto error; if (!ciphers) ciphers = GIT_SSL_DEFAULT_CIPHERS; if(!SSL_CTX_set_cipher_list(git__ssl_ctx, ciphers)) goto error; if (init_bio_method() < 0) goto error; return git_runtime_shutdown_register(shutdown_ssl); error: git_error_set(GIT_ERROR_NET, "could not initialize openssl: %s", ERR_error_string(ERR_get_error(), NULL)); SSL_CTX_free(git__ssl_ctx); git__ssl_ctx = NULL; return -1; } /* * When we use dynamic loading, we defer OpenSSL initialization until * it's first used. `openssl_ensure_initialized` will do the work * under a mutex. */ git_mutex openssl_mutex; bool openssl_initialized; int git_openssl_stream_global_init(void) { #ifndef GIT_OPENSSL_DYNAMIC return openssl_init(); #else if (git_mutex_init(&openssl_mutex) != 0) return -1; return 0; #endif } static int openssl_ensure_initialized(void) { #ifdef GIT_OPENSSL_DYNAMIC int error = 0; if (git_mutex_lock(&openssl_mutex) != 0) return -1; if (!openssl_initialized) { if ((error = git_openssl_stream_dynamic_init()) == 0) error = openssl_init(); openssl_initialized = true; } error |= git_mutex_unlock(&openssl_mutex); return error; #else return 0; #endif } #if !defined(GIT_OPENSSL_LEGACY) && !defined(GIT_OPENSSL_DYNAMIC) int git_openssl_set_locking(void) { # ifdef GIT_THREADS return 0; # else git_error_set(GIT_ERROR_THREAD, "libgit2 was not built with threads"); return -1; # endif } #endif static int bio_create(BIO *b) { BIO_set_init(b, 1); BIO_set_data(b, NULL); return 1; } static int bio_destroy(BIO *b) { if (!b) return 0; BIO_set_data(b, NULL); return 1; } static int bio_read(BIO *b, char *buf, int len) { git_stream *io = (git_stream *) BIO_get_data(b); return (int) git_stream_read(io, buf, len); } static int bio_write(BIO *b, const char *buf, int len) { git_stream *io = (git_stream *) BIO_get_data(b); return (int) git_stream_write(io, buf, len, 0); } static long bio_ctrl(BIO *b, int cmd, long num, void *ptr) { GIT_UNUSED(b); GIT_UNUSED(num); GIT_UNUSED(ptr); if (cmd == BIO_CTRL_FLUSH) return 1; return 0; } static int bio_gets(BIO *b, char *buf, int len) { GIT_UNUSED(b); GIT_UNUSED(buf); GIT_UNUSED(len); return -1; } static int bio_puts(BIO *b, const char *str) { return bio_write(b, str, strlen(str)); } static int init_bio_method(void) { /* Set up the BIO_METHOD we use for wrapping our own stream implementations */ git_stream_bio_method = BIO_meth_new(BIO_TYPE_SOURCE_SINK | BIO_get_new_index(), "git_stream"); GIT_ERROR_CHECK_ALLOC(git_stream_bio_method); BIO_meth_set_write(git_stream_bio_method, bio_write); BIO_meth_set_read(git_stream_bio_method, bio_read); BIO_meth_set_puts(git_stream_bio_method, bio_puts); BIO_meth_set_gets(git_stream_bio_method, bio_gets); BIO_meth_set_ctrl(git_stream_bio_method, bio_ctrl); BIO_meth_set_create(git_stream_bio_method, bio_create); BIO_meth_set_destroy(git_stream_bio_method, bio_destroy); return 0; } static int ssl_set_error(SSL *ssl, int error) { int err; unsigned long e; err = SSL_get_error(ssl, error); GIT_ASSERT(err != SSL_ERROR_WANT_READ); GIT_ASSERT(err != SSL_ERROR_WANT_WRITE); switch (err) { case SSL_ERROR_WANT_CONNECT: case SSL_ERROR_WANT_ACCEPT: git_error_set(GIT_ERROR_SSL, "SSL error: connection failure"); break; case SSL_ERROR_WANT_X509_LOOKUP: git_error_set(GIT_ERROR_SSL, "SSL error: x509 error"); break; case SSL_ERROR_SYSCALL: e = ERR_get_error(); if (e > 0) { char errmsg[256]; ERR_error_string_n(e, errmsg, sizeof(errmsg)); git_error_set(GIT_ERROR_NET, "SSL error: %s", errmsg); break; } else if (error < 0) { git_error_set(GIT_ERROR_OS, "SSL error: syscall failure"); break; } git_error_set(GIT_ERROR_SSL, "SSL error: received early EOF"); return GIT_EEOF; break; case SSL_ERROR_SSL: { char errmsg[256]; e = ERR_get_error(); ERR_error_string_n(e, errmsg, sizeof(errmsg)); git_error_set(GIT_ERROR_SSL, "SSL error: %s", errmsg); break; } case SSL_ERROR_NONE: case SSL_ERROR_ZERO_RETURN: default: git_error_set(GIT_ERROR_SSL, "SSL error: unknown error"); break; } return -1; } static int ssl_teardown(SSL *ssl) { int ret; ret = SSL_shutdown(ssl); if (ret < 0) ret = ssl_set_error(ssl, ret); else ret = 0; return ret; } static int check_host_name(const char *name, const char *host) { if (!strcasecmp(name, host)) return 0; if (gitno__match_host(name, host) < 0) return -1; return 0; } static int verify_server_cert(SSL *ssl, const char *host) { X509 *cert = NULL; X509_NAME *peer_name; ASN1_STRING *str; unsigned char *peer_cn = NULL; int matched = -1, type = GEN_DNS; GENERAL_NAMES *alts; struct in6_addr addr6; struct in_addr addr4; void *addr = NULL; int i = -1, j, error = 0; if (SSL_get_verify_result(ssl) != X509_V_OK) { git_error_set(GIT_ERROR_SSL, "the SSL certificate is invalid"); return GIT_ECERTIFICATE; } /* Try to parse the host as an IP address to see if it is */ if (p_inet_pton(AF_INET, host, &addr4)) { type = GEN_IPADD; addr = &addr4; } else { if (p_inet_pton(AF_INET6, host, &addr6)) { type = GEN_IPADD; addr = &addr6; } } cert = SSL_get_peer_certificate(ssl); if (!cert) { error = -1; git_error_set(GIT_ERROR_SSL, "the server did not provide a certificate"); goto cleanup; } /* Check the alternative names */ alts = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL); if (alts) { int num; num = sk_GENERAL_NAME_num(alts); for (i = 0; i < num && matched != 1; i++) { const GENERAL_NAME *gn = sk_GENERAL_NAME_value(alts, i); const char *name = (char *) ASN1_STRING_get0_data(gn->d.ia5); size_t namelen = (size_t) ASN1_STRING_length(gn->d.ia5); /* Skip any names of a type we're not looking for */ if (gn->type != type) continue; if (type == GEN_DNS) { /* If it contains embedded NULs, don't even try */ if (memchr(name, '\0', namelen)) continue; if (check_host_name(name, host) < 0) matched = 0; else matched = 1; } else if (type == GEN_IPADD) { /* Here name isn't so much a name but a binary representation of the IP */ matched = addr && !!memcmp(name, addr, namelen); } } } GENERAL_NAMES_free(alts); if (matched == 0) goto cert_fail_name; if (matched == 1) { goto cleanup; } /* If no alternative names are available, check the common name */ peer_name = X509_get_subject_name(cert); if (peer_name == NULL) goto on_error; if (peer_name) { /* Get the index of the last CN entry */ while ((j = X509_NAME_get_index_by_NID(peer_name, NID_commonName, i)) >= 0) i = j; } if (i < 0) goto on_error; str = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(peer_name, i)); if (str == NULL) goto on_error; /* Work around a bug in OpenSSL whereby ASN1_STRING_to_UTF8 fails if it's already in utf-8 */ if (ASN1_STRING_type(str) == V_ASN1_UTF8STRING) { int size = ASN1_STRING_length(str); if (size > 0) { peer_cn = OPENSSL_malloc(size + 1); GIT_ERROR_CHECK_ALLOC(peer_cn); memcpy(peer_cn, ASN1_STRING_get0_data(str), size); peer_cn[size] = '\0'; } else { goto cert_fail_name; } } else { int size = ASN1_STRING_to_UTF8(&peer_cn, str); GIT_ERROR_CHECK_ALLOC(peer_cn); if (memchr(peer_cn, '\0', size)) goto cert_fail_name; } if (check_host_name((char *)peer_cn, host) < 0) goto cert_fail_name; goto cleanup; cert_fail_name: error = GIT_ECERTIFICATE; git_error_set(GIT_ERROR_SSL, "hostname does not match certificate"); goto cleanup; on_error: error = ssl_set_error(ssl, 0); goto cleanup; cleanup: X509_free(cert); OPENSSL_free(peer_cn); return error; } typedef struct { git_stream parent; git_stream *io; int owned; bool connected; char *host; SSL *ssl; git_cert_x509 cert_info; } openssl_stream; static int openssl_connect(git_stream *stream) { int ret; BIO *bio; openssl_stream *st = (openssl_stream *) stream; if (st->owned && (ret = git_stream_connect(st->io)) < 0) return ret; bio = BIO_new(git_stream_bio_method); GIT_ERROR_CHECK_ALLOC(bio); BIO_set_data(bio, st->io); SSL_set_bio(st->ssl, bio, bio); /* specify the host in case SNI is needed */ #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME SSL_set_tlsext_host_name(st->ssl, st->host); #endif if ((ret = SSL_connect(st->ssl)) <= 0) return ssl_set_error(st->ssl, ret); st->connected = true; return verify_server_cert(st->ssl, st->host); } static int openssl_certificate(git_cert **out, git_stream *stream) { openssl_stream *st = (openssl_stream *) stream; X509 *cert = SSL_get_peer_certificate(st->ssl); unsigned char *guard, *encoded_cert = NULL; int error, len; /* Retrieve the length of the certificate first */ len = i2d_X509(cert, NULL); if (len < 0) { git_error_set(GIT_ERROR_NET, "failed to retrieve certificate information"); error = -1; goto out; } encoded_cert = git__malloc(len); GIT_ERROR_CHECK_ALLOC(encoded_cert); /* i2d_X509 makes 'guard' point to just after the data */ guard = encoded_cert; len = i2d_X509(cert, &guard); if (len < 0) { git_error_set(GIT_ERROR_NET, "failed to retrieve certificate information"); error = -1; goto out; } st->cert_info.parent.cert_type = GIT_CERT_X509; st->cert_info.data = encoded_cert; st->cert_info.len = len; encoded_cert = NULL; *out = &st->cert_info.parent; error = 0; out: git__free(encoded_cert); X509_free(cert); return error; } static int openssl_set_proxy(git_stream *stream, const git_proxy_options *proxy_opts) { openssl_stream *st = (openssl_stream *) stream; return git_stream_set_proxy(st->io, proxy_opts); } static ssize_t openssl_write(git_stream *stream, const char *data, size_t data_len, int flags) { openssl_stream *st = (openssl_stream *) stream; int ret, len = min(data_len, INT_MAX); GIT_UNUSED(flags); if ((ret = SSL_write(st->ssl, data, len)) <= 0) return ssl_set_error(st->ssl, ret); return ret; } static ssize_t openssl_read(git_stream *stream, void *data, size_t len) { openssl_stream *st = (openssl_stream *) stream; int ret; if ((ret = SSL_read(st->ssl, data, len)) <= 0) return ssl_set_error(st->ssl, ret); return ret; } static int openssl_close(git_stream *stream) { openssl_stream *st = (openssl_stream *) stream; int ret; if (st->connected && (ret = ssl_teardown(st->ssl)) < 0) return -1; st->connected = false; return st->owned ? git_stream_close(st->io) : 0; } static void openssl_free(git_stream *stream) { openssl_stream *st = (openssl_stream *) stream; if (st->owned) git_stream_free(st->io); SSL_free(st->ssl); git__free(st->host); git__free(st->cert_info.data); git__free(st); } static int openssl_stream_wrap( git_stream **out, git_stream *in, const char *host, int owned) { openssl_stream *st; GIT_ASSERT_ARG(out); GIT_ASSERT_ARG(in); GIT_ASSERT_ARG(host); st = git__calloc(1, sizeof(openssl_stream)); GIT_ERROR_CHECK_ALLOC(st); st->io = in; st->owned = owned; st->ssl = SSL_new(git__ssl_ctx); if (st->ssl == NULL) { git_error_set(GIT_ERROR_SSL, "failed to create ssl object"); git__free(st); return -1; } st->host = git__strdup(host); GIT_ERROR_CHECK_ALLOC(st->host); st->parent.version = GIT_STREAM_VERSION; st->parent.encrypted = 1; st->parent.proxy_support = git_stream_supports_proxy(st->io); st->parent.connect = openssl_connect; st->parent.certificate = openssl_certificate; st->parent.set_proxy = openssl_set_proxy; st->parent.read = openssl_read; st->parent.write = openssl_write; st->parent.close = openssl_close; st->parent.free = openssl_free; *out = (git_stream *) st; return 0; } int git_openssl_stream_wrap(git_stream **out, git_stream *in, const char *host) { if (openssl_ensure_initialized() < 0) return -1; return openssl_stream_wrap(out, in, host, 0); } int git_openssl_stream_new(git_stream **out, const char *host, const char *port) { git_stream *stream = NULL; int error; GIT_ASSERT_ARG(out); GIT_ASSERT_ARG(host); GIT_ASSERT_ARG(port); if (openssl_ensure_initialized() < 0) return -1; if ((error = git_socket_stream_new(&stream, host, port)) < 0) return error; if ((error = openssl_stream_wrap(out, stream, host, 1)) < 0) { git_stream_close(stream); git_stream_free(stream); } return error; } int git_openssl__set_cert_location(const char *file, const char *path) { if (openssl_ensure_initialized() < 0) return -1; if (SSL_CTX_load_verify_locations(git__ssl_ctx, file, path) == 0) { char errmsg[256]; ERR_error_string_n(ERR_get_error(), errmsg, sizeof(errmsg)); git_error_set(GIT_ERROR_SSL, "OpenSSL error: failed to load certificates: %s", errmsg); return -1; } return 0; } #else #include "stream.h" #include "git2/sys/openssl.h" int git_openssl_stream_global_init(void) { return 0; } int git_openssl_set_locking(void) { git_error_set(GIT_ERROR_SSL, "libgit2 was not built with OpenSSL support"); return -1; } #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/streams/openssl_legacy.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_streams_openssl_legacy_h__ #define INCLUDE_streams_openssl_legacy_h__ #include "streams/openssl_dynamic.h" #if defined(GIT_OPENSSL) && !defined(GIT_OPENSSL_DYNAMIC) # include <openssl/ssl.h> # include <openssl/err.h> # include <openssl/x509v3.h> # include <openssl/bio.h> # if (defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER < 0x10100000L) || \ (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20700000L) # define GIT_OPENSSL_LEGACY # endif #endif #if defined(GIT_OPENSSL_LEGACY) && !defined(GIT_OPENSSL_DYNAMIC) # define OPENSSL_init_ssl OPENSSL_init_ssl__legacy # define BIO_meth_new BIO_meth_new__legacy # define BIO_meth_free BIO_meth_free__legacy # define BIO_meth_set_write BIO_meth_set_write__legacy # define BIO_meth_set_read BIO_meth_set_read__legacy # define BIO_meth_set_puts BIO_meth_set_puts__legacy # define BIO_meth_set_gets BIO_meth_set_gets__legacy # define BIO_meth_set_ctrl BIO_meth_set_ctrl__legacy # define BIO_meth_set_create BIO_meth_set_create__legacy # define BIO_meth_set_destroy BIO_meth_set_destroy__legacy # define BIO_get_new_index BIO_get_new_index__legacy # define BIO_set_data BIO_set_data__legacy # define BIO_set_init BIO_set_init__legacy # define BIO_get_data BIO_get_data__legacy # define ASN1_STRING_get0_data ASN1_STRING_get0_data__legacy #endif #if defined(GIT_OPENSSL_LEGACY) || defined(GIT_OPENSSL_DYNAMIC) extern int OPENSSL_init_ssl__legacy(uint64_t opts, const void *settings); extern BIO_METHOD *BIO_meth_new__legacy(int type, const char *name); extern void BIO_meth_free__legacy(BIO_METHOD *biom); extern int BIO_meth_set_write__legacy(BIO_METHOD *biom, int (*write) (BIO *, const char *, int)); extern int BIO_meth_set_read__legacy(BIO_METHOD *biom, int (*read) (BIO *, char *, int)); extern int BIO_meth_set_puts__legacy(BIO_METHOD *biom, int (*puts) (BIO *, const char *)); extern int BIO_meth_set_gets__legacy(BIO_METHOD *biom, int (*gets) (BIO *, char *, int)); extern int BIO_meth_set_ctrl__legacy(BIO_METHOD *biom, long (*ctrl) (BIO *, int, long, void *)); extern int BIO_meth_set_create__legacy(BIO_METHOD *biom, int (*create) (BIO *)); extern int BIO_meth_set_destroy__legacy(BIO_METHOD *biom, int (*destroy) (BIO *)); extern int BIO_get_new_index__legacy(void); extern void BIO_set_data__legacy(BIO *a, void *ptr); extern void BIO_set_init__legacy(BIO *b, int init); extern void *BIO_get_data__legacy(BIO *a); extern const unsigned char *ASN1_STRING_get0_data__legacy(const ASN1_STRING *x); extern long SSL_CTX_set_options__legacy(SSL_CTX *ctx, long op); #endif #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/streams/openssl_dynamic.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "streams/openssl.h" #include "streams/openssl_dynamic.h" #if defined(GIT_OPENSSL) && defined(GIT_OPENSSL_DYNAMIC) #include "runtime.h" #include <dlfcn.h> unsigned char *(*ASN1_STRING_data)(ASN1_STRING *x); const unsigned char *(*ASN1_STRING_get0_data)(const ASN1_STRING *x); int (*ASN1_STRING_length)(const ASN1_STRING *x); int (*ASN1_STRING_to_UTF8)(unsigned char **out, const ASN1_STRING *in); int (*ASN1_STRING_type)(const ASN1_STRING *x); void *(*BIO_get_data)(BIO *a); int (*BIO_get_new_index)(void); int (*OPENSSL_init_ssl)(uint64_t opts, const void *settings); void (*BIO_meth_free)(BIO_METHOD *biom); int (*BIO_meth_set_create)(BIO_METHOD *biom, int (*create) (BIO *)); int (*BIO_meth_set_ctrl)(BIO_METHOD *biom, long (*ctrl) (BIO *, int, long, void *)); int (*BIO_meth_set_destroy)(BIO_METHOD *biom, int (*destroy) (BIO *)); int (*BIO_meth_set_gets)(BIO_METHOD *biom, int (*gets) (BIO *, char *, int)); int (*BIO_meth_set_puts)(BIO_METHOD *biom, int (*puts) (BIO *, const char *)); int (*BIO_meth_set_read)(BIO_METHOD *biom, int (*read) (BIO *, char *, int)); int (*BIO_meth_set_write)(BIO_METHOD *biom, int (*write) (BIO *, const char *, int)); BIO_METHOD *(*BIO_meth_new)(int type, const char *name); BIO *(*BIO_new)(const BIO_METHOD *type); void (*BIO_set_data)(BIO *a, void *ptr); void (*BIO_set_init)(BIO *a, int init); void (*CRYPTO_free)(void *ptr, const char *file, int line); void *(*CRYPTO_malloc)(size_t num, const char *file, int line); int (*CRYPTO_num_locks)(void); void (*CRYPTO_set_locking_callback)(void (*func)(int mode, int type, const char *file, int line)); int (*CRYPTO_set_mem_functions)(void *(*m)(size_t bytes), void *(*r)(void *mem, size_t size), void (*f)(void *mem)); int (*CRYPTO_THREADID_set_callback)(void (*func)(CRYPTO_THREADID *id)); void (*CRYPTO_THREADID_set_numeric)(CRYPTO_THREADID *id, unsigned long val); char *(*ERR_error_string)(unsigned long e, char *buf); void (*ERR_error_string_n)(unsigned long e, char *buf, size_t len); unsigned long (*ERR_get_error)(void); int (*SSL_connect)(SSL *ssl); long (*SSL_ctrl)(SSL *ssl, int cmd, long arg, void *parg); void (*SSL_free)(SSL *ssl); int (*SSL_get_error)(SSL *ssl, int ret); X509 *(*SSL_get_peer_certificate)(const SSL *ssl); long (*SSL_get_verify_result)(const SSL *ssl); int (*SSL_library_init)(void); void (*SSL_load_error_strings)(void); SSL *(*SSL_new)(SSL_CTX *ctx); int (*SSL_read)(SSL *ssl, const void *buf, int num); void (*SSL_set_bio)(SSL *ssl, BIO *rbio, BIO *wbio); int (*SSL_shutdown)(SSL *ssl); int (*SSL_write)(SSL *ssl, const void *buf, int num); long (*SSL_CTX_ctrl)(SSL_CTX *ctx, int cmd, long larg, void *parg); void (*SSL_CTX_free)(SSL_CTX *ctx); SSL_CTX *(*SSL_CTX_new)(const SSL_METHOD *method); int (*SSL_CTX_set_cipher_list)(SSL_CTX *ctx, const char *str); int (*SSL_CTX_set_default_verify_paths)(SSL_CTX *ctx); long (*SSL_CTX_set_options)(SSL_CTX *ctx, long options); void (*SSL_CTX_set_verify)(SSL_CTX *ctx, int mode, int (*verify_callback)(int, X509_STORE_CTX *)); int (*SSL_CTX_load_verify_locations)(SSL_CTX *ctx, const char *CAfile, const char *CApath); const SSL_METHOD *(*SSLv23_method)(void); const SSL_METHOD *(*TLS_method)(void); ASN1_STRING *(*X509_NAME_ENTRY_get_data)(const X509_NAME_ENTRY *ne); X509_NAME_ENTRY *(*X509_NAME_get_entry)(X509_NAME *name, int loc); int (*X509_NAME_get_index_by_NID)(X509_NAME *name, int nid, int lastpos); void (*X509_free)(X509 *a); void *(*X509_get_ext_d2i)(const X509 *x, int nid, int *crit, int *idx); X509_NAME *(*X509_get_subject_name)(const X509 *x); int (*i2d_X509)(X509 *a, unsigned char **ppout); int (*OPENSSL_sk_num)(const void *sk); void *(*OPENSSL_sk_value)(const void *sk, int i); void (*OPENSSL_sk_free)(void *sk); int (*sk_num)(const void *sk); void *(*sk_value)(const void *sk, int i); void (*sk_free)(void *sk); void *openssl_handle; GIT_INLINE(void *) openssl_sym(int *err, const char *name, bool required) { void *symbol; /* if we've seen an err, noop to retain it */ if (*err) return NULL; if ((symbol = dlsym(openssl_handle, name)) == NULL && required) { const char *msg = dlerror(); git_error_set(GIT_ERROR_SSL, "could not load ssl function '%s': %s", name, msg ? msg : "unknown error"); *err = -1; } return symbol; } static void dynamic_shutdown(void) { dlclose(openssl_handle); openssl_handle = NULL; } int git_openssl_stream_dynamic_init(void) { int err = 0; if ((openssl_handle = dlopen("libssl.so.1.1", RTLD_NOW)) == NULL && (openssl_handle = dlopen("libssl.1.1.dylib", RTLD_NOW)) == NULL && (openssl_handle = dlopen("libssl.so.1.0.0", RTLD_NOW)) == NULL && (openssl_handle = dlopen("libssl.1.0.0.dylib", RTLD_NOW)) == NULL && (openssl_handle = dlopen("libssl.so.10", RTLD_NOW)) == NULL) { git_error_set(GIT_ERROR_SSL, "could not load ssl libraries"); return -1; } ASN1_STRING_data = (unsigned char *(*)(ASN1_STRING *x))openssl_sym(&err, "ASN1_STRING_data", false); ASN1_STRING_get0_data = (const unsigned char *(*)(const ASN1_STRING *x))openssl_sym(&err, "ASN1_STRING_get0_data", false); ASN1_STRING_length = (int (*)(const ASN1_STRING *))openssl_sym(&err, "ASN1_STRING_length", true); ASN1_STRING_to_UTF8 = (int (*)(unsigned char **, const ASN1_STRING *))openssl_sym(&err, "ASN1_STRING_to_UTF8", true); ASN1_STRING_type = (int (*)(const ASN1_STRING *))openssl_sym(&err, "ASN1_STRING_type", true); BIO_get_data = (void *(*)(BIO *))openssl_sym(&err, "BIO_get_data", false); BIO_get_new_index = (int (*)(void))openssl_sym(&err, "BIO_get_new_index", false); BIO_meth_free = (void (*)(BIO_METHOD *))openssl_sym(&err, "BIO_meth_free", false); BIO_meth_new = (BIO_METHOD *(*)(int, const char *))openssl_sym(&err, "BIO_meth_new", false); BIO_meth_set_create = (int (*)(BIO_METHOD *, int (*)(BIO *)))openssl_sym(&err, "BIO_meth_set_create", false); BIO_meth_set_ctrl = (int (*)(BIO_METHOD *, long (*)(BIO *, int, long, void *)))openssl_sym(&err, "BIO_meth_set_ctrl", false); BIO_meth_set_destroy = (int (*)(BIO_METHOD *, int (*)(BIO *)))openssl_sym(&err, "BIO_meth_set_destroy", false); BIO_meth_set_gets = (int (*)(BIO_METHOD *, int (*)(BIO *, char *, int)))openssl_sym(&err, "BIO_meth_set_gets", false); BIO_meth_set_puts = (int (*)(BIO_METHOD *, int (*)(BIO *, const char *)))openssl_sym(&err, "BIO_meth_set_puts", false); BIO_meth_set_read = (int (*)(BIO_METHOD *, int (*)(BIO *, char *, int)))openssl_sym(&err, "BIO_meth_set_read", false); BIO_meth_set_write = (int (*)(BIO_METHOD *, int (*)(BIO *, const char *, int)))openssl_sym(&err, "BIO_meth_set_write", false); BIO_new = (BIO *(*)(const BIO_METHOD *))openssl_sym(&err, "BIO_new", true); BIO_set_data = (void (*)(BIO *a, void *))openssl_sym(&err, "BIO_set_data", false); BIO_set_init = (void (*)(BIO *a, int))openssl_sym(&err, "BIO_set_init", false); CRYPTO_free = (void (*)(void *, const char *, int))openssl_sym(&err, "CRYPTO_free", true); CRYPTO_malloc = (void *(*)(size_t, const char *, int))openssl_sym(&err, "CRYPTO_malloc", true); CRYPTO_num_locks = (int (*)(void))openssl_sym(&err, "CRYPTO_num_locks", false); CRYPTO_set_locking_callback = (void (*)(void (*)(int, int, const char *, int)))openssl_sym(&err, "CRYPTO_set_locking_callback", false); CRYPTO_set_mem_functions = (int (*)(void *(*)(size_t), void *(*)(void *, size_t), void (*f)(void *)))openssl_sym(&err, "CRYPTO_set_mem_functions", true); CRYPTO_THREADID_set_callback = (int (*)(void (*)(CRYPTO_THREADID *)))openssl_sym(&err, "CRYPTO_THREADID_set_callback", false); CRYPTO_THREADID_set_numeric = (void (*)(CRYPTO_THREADID *, unsigned long))openssl_sym(&err, "CRYPTO_THREADID_set_numeric", false); ERR_error_string = (char *(*)(unsigned long, char *))openssl_sym(&err, "ERR_error_string", true); ERR_error_string_n = (void (*)(unsigned long, char *, size_t))openssl_sym(&err, "ERR_error_string_n", true); ERR_get_error = (unsigned long (*)(void))openssl_sym(&err, "ERR_get_error", true); OPENSSL_init_ssl = (int (*)(uint64_t opts, const void *settings))openssl_sym(&err, "OPENSSL_init_ssl", false); OPENSSL_sk_num = (int (*)(const void *))openssl_sym(&err, "OPENSSL_sk_num", false); OPENSSL_sk_value = (void *(*)(const void *sk, int i))openssl_sym(&err, "OPENSSL_sk_value", false); OPENSSL_sk_free = (void (*)(void *))openssl_sym(&err, "OPENSSL_sk_free", false); sk_num = (int (*)(const void *))openssl_sym(&err, "sk_num", false); sk_value = (void *(*)(const void *sk, int i))openssl_sym(&err, "sk_value", false); sk_free = (void (*)(void *))openssl_sym(&err, "sk_free", false); SSL_connect = (int (*)(SSL *))openssl_sym(&err, "SSL_connect", true); SSL_ctrl = (long (*)(SSL *, int, long, void *))openssl_sym(&err, "SSL_ctrl", true); SSL_get_peer_certificate = (X509 *(*)(const SSL *))openssl_sym(&err, "SSL_get_peer_certificate", true); SSL_library_init = (int (*)(void))openssl_sym(&err, "SSL_library_init", false); SSL_free = (void (*)(SSL *))openssl_sym(&err, "SSL_free", true); SSL_get_error = (int (*)(SSL *, int))openssl_sym(&err, "SSL_get_error", true); SSL_get_verify_result = (long (*)(const SSL *ssl))openssl_sym(&err, "SSL_get_verify_result", true); SSL_load_error_strings = (void (*)(void))openssl_sym(&err, "SSL_load_error_strings", false); SSL_new = (SSL *(*)(SSL_CTX *))openssl_sym(&err, "SSL_new", true); SSL_read = (int (*)(SSL *, const void *, int))openssl_sym(&err, "SSL_read", true); SSL_set_bio = (void (*)(SSL *, BIO *, BIO *))openssl_sym(&err, "SSL_set_bio", true); SSL_shutdown = (int (*)(SSL *ssl))openssl_sym(&err, "SSL_shutdown", true); SSL_write = (int (*)(SSL *, const void *, int))openssl_sym(&err, "SSL_write", true); SSL_CTX_ctrl = (long (*)(SSL_CTX *, int, long, void *))openssl_sym(&err, "SSL_CTX_ctrl", true); SSL_CTX_free = (void (*)(SSL_CTX *))openssl_sym(&err, "SSL_CTX_free", true); SSL_CTX_new = (SSL_CTX *(*)(const SSL_METHOD *))openssl_sym(&err, "SSL_CTX_new", true); SSL_CTX_set_cipher_list = (int (*)(SSL_CTX *, const char *))openssl_sym(&err, "SSL_CTX_set_cipher_list", true); SSL_CTX_set_default_verify_paths = (int (*)(SSL_CTX *ctx))openssl_sym(&err, "SSL_CTX_set_default_verify_paths", true); SSL_CTX_set_options = (long (*)(SSL_CTX *, long))openssl_sym(&err, "SSL_CTX_set_options", false); SSL_CTX_set_verify = (void (*)(SSL_CTX *, int, int (*)(int, X509_STORE_CTX *)))openssl_sym(&err, "SSL_CTX_set_verify", true); SSL_CTX_load_verify_locations = (int (*)(SSL_CTX *, const char *, const char *))openssl_sym(&err, "SSL_CTX_load_verify_locations", true); SSLv23_method = (const SSL_METHOD *(*)(void))openssl_sym(&err, "SSLv23_method", false); TLS_method = (const SSL_METHOD *(*)(void))openssl_sym(&err, "TLS_method", false); X509_NAME_ENTRY_get_data = (ASN1_STRING *(*)(const X509_NAME_ENTRY *))openssl_sym(&err, "X509_NAME_ENTRY_get_data", true); X509_NAME_get_entry = (X509_NAME_ENTRY *(*)(X509_NAME *, int))openssl_sym(&err, "X509_NAME_get_entry", true); X509_NAME_get_index_by_NID = (int (*)(X509_NAME *, int, int))openssl_sym(&err, "X509_NAME_get_index_by_NID", true); X509_free = (void (*)(X509 *))openssl_sym(&err, "X509_free", true); X509_get_ext_d2i = (void *(*)(const X509 *x, int nid, int *crit, int *idx))openssl_sym(&err, "X509_get_ext_d2i", true); X509_get_subject_name = (X509_NAME *(*)(const X509 *))openssl_sym(&err, "X509_get_subject_name", true); i2d_X509 = (int (*)(X509 *a, unsigned char **ppout))openssl_sym(&err, "i2d_X509", true); if (err) goto on_error; /* Add legacy functionality */ if (!OPENSSL_init_ssl) { OPENSSL_init_ssl = OPENSSL_init_ssl__legacy; if (!SSL_library_init || !SSL_load_error_strings || !CRYPTO_num_locks || !CRYPTO_set_locking_callback || !CRYPTO_THREADID_set_callback || !CRYPTO_THREADID_set_numeric) { git_error_set(GIT_ERROR_SSL, "could not load legacy openssl initialization functions"); goto on_error; } } if (!SSL_CTX_set_options) SSL_CTX_set_options = SSL_CTX_set_options__legacy; if (TLS_method) SSLv23_method = TLS_method; if (!BIO_meth_new) { BIO_meth_new = BIO_meth_new__legacy; BIO_meth_new = BIO_meth_new__legacy; BIO_meth_free = BIO_meth_free__legacy; BIO_meth_set_write = BIO_meth_set_write__legacy; BIO_meth_set_read = BIO_meth_set_read__legacy; BIO_meth_set_puts = BIO_meth_set_puts__legacy; BIO_meth_set_gets = BIO_meth_set_gets__legacy; BIO_meth_set_ctrl = BIO_meth_set_ctrl__legacy; BIO_meth_set_create = BIO_meth_set_create__legacy; BIO_meth_set_destroy = BIO_meth_set_destroy__legacy; BIO_get_new_index = BIO_get_new_index__legacy; BIO_set_data = BIO_set_data__legacy; BIO_set_init = BIO_set_init__legacy; BIO_get_data = BIO_get_data__legacy; } if (!ASN1_STRING_get0_data) { if (!ASN1_STRING_data) { git_error_set(GIT_ERROR_SSL, "could not load legacy openssl string function"); goto on_error; } ASN1_STRING_get0_data = ASN1_STRING_get0_data__legacy; } if ((!OPENSSL_sk_num && !sk_num) || (!OPENSSL_sk_value && !sk_value) || (!OPENSSL_sk_free && !sk_free)) { git_error_set(GIT_ERROR_SSL, "could not load legacy openssl stack functions"); goto on_error; } if (git_runtime_shutdown_register(dynamic_shutdown) != 0) goto on_error; return 0; on_error: dlclose(openssl_handle); return -1; } int sk_GENERAL_NAME_num(const GENERAL_NAME *sk) { if (OPENSSL_sk_num) return OPENSSL_sk_num(sk); else if (sk_num) return sk_num(sk); GIT_ASSERT_WITH_RETVAL(false, 0); return 0; } GENERAL_NAME *sk_GENERAL_NAME_value(const GENERAL_NAME *sk, int i) { if (OPENSSL_sk_value) return OPENSSL_sk_value(sk, i); else if (sk_value) return sk_value(sk, i); GIT_ASSERT_WITH_RETVAL(false, NULL); return NULL; } void GENERAL_NAMES_free(GENERAL_NAME *sk) { if (OPENSSL_sk_free) OPENSSL_sk_free(sk); else if (sk_free) sk_free(sk); } #endif /* GIT_OPENSSL && GIT_OPENSSL_DYNAMIC */
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/streams/registry.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "common.h" #include "streams/registry.h" #include "runtime.h" #include "streams/tls.h" #include "streams/mbedtls.h" #include "streams/openssl.h" #include "streams/stransport.h" struct stream_registry { git_rwlock lock; git_stream_registration callbacks; git_stream_registration tls_callbacks; }; static struct stream_registry stream_registry; static void shutdown_stream_registry(void) { git_rwlock_free(&stream_registry.lock); } int git_stream_registry_global_init(void) { if (git_rwlock_init(&stream_registry.lock) < 0) return -1; return git_runtime_shutdown_register(shutdown_stream_registry); } GIT_INLINE(void) stream_registration_cpy( git_stream_registration *target, git_stream_registration *src) { if (src) memcpy(target, src, sizeof(git_stream_registration)); else memset(target, 0, sizeof(git_stream_registration)); } int git_stream_registry_lookup(git_stream_registration *out, git_stream_t type) { git_stream_registration *target; int error = GIT_ENOTFOUND; GIT_ASSERT_ARG(out); switch(type) { case GIT_STREAM_STANDARD: target = &stream_registry.callbacks; break; case GIT_STREAM_TLS: target = &stream_registry.tls_callbacks; break; default: git_error_set(GIT_ERROR_INVALID, "invalid stream type"); return -1; } if (git_rwlock_rdlock(&stream_registry.lock) < 0) { git_error_set(GIT_ERROR_OS, "failed to lock stream registry"); return -1; } if (target->init) { stream_registration_cpy(out, target); error = 0; } git_rwlock_rdunlock(&stream_registry.lock); return error; } int git_stream_register(git_stream_t type, git_stream_registration *registration) { GIT_ASSERT(!registration || registration->init); GIT_ERROR_CHECK_VERSION(registration, GIT_STREAM_VERSION, "stream_registration"); if (git_rwlock_wrlock(&stream_registry.lock) < 0) { git_error_set(GIT_ERROR_OS, "failed to lock stream registry"); return -1; } if ((type & GIT_STREAM_STANDARD) == GIT_STREAM_STANDARD) stream_registration_cpy(&stream_registry.callbacks, registration); if ((type & GIT_STREAM_TLS) == GIT_STREAM_TLS) stream_registration_cpy(&stream_registry.tls_callbacks, registration); git_rwlock_wrunlock(&stream_registry.lock); return 0; } #ifndef GIT_DEPRECATE_HARD int git_stream_register_tls( int GIT_CALLBACK(ctor)(git_stream **out, const char *host, const char *port)) { git_stream_registration registration = {0}; if (ctor) { registration.version = GIT_STREAM_VERSION; registration.init = ctor; registration.wrap = NULL; return git_stream_register(GIT_STREAM_TLS, &registration); } else { return git_stream_register(GIT_STREAM_TLS, NULL); } } #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/streams/openssl_dynamic.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ /* Copyright (C) 1995-1998 Eric Young ([email protected]) * All rights reserved. * * This package is an SSL implementation written * by Eric Young ([email protected]). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson ([email protected]). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * 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 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young ([email protected])" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson ([email protected])" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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 AUTHOR 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. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ /* ==================================================================== * Copyright (c) 1998-2007 The OpenSSL Project. 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. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * [email protected]. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED 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 OpenSSL PROJECT OR * ITS 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. * ==================================================================== * * This product includes cryptographic software written by Eric Young * ([email protected]). This product includes software written by Tim * Hudson ([email protected]). * */ /* ==================================================================== * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. * ECC cipher suite support in OpenSSL originally developed by * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. */ /* ==================================================================== * Copyright 2005 Nokia. All rights reserved. * * The portions of the attached software ("Contribution") is developed by * Nokia Corporation and is licensed pursuant to the OpenSSL open source * license. * * The Contribution, originally written by Mika Kousa and Pasi Eronen of * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites * support (see RFC 4279) to OpenSSL. * * No patent licenses or other rights except those expressly stated in * the OpenSSL open source license shall be deemed granted or received * expressly, by implication, estoppel, or otherwise. * * No assurances are provided by Nokia that the Contribution does not * infringe the patent or other intellectual property rights of any third * party or that the license provides you with all the necessary rights * to make use of the Contribution. * * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR * OTHERWISE. */ #ifndef INCLUDE_streams_openssl_dynamic_h__ #define INCLUDE_streams_openssl_dynamic_h__ #ifdef GIT_OPENSSL_DYNAMIC # define BIO_CTRL_FLUSH 11 # define BIO_TYPE_SOURCE_SINK 0x0400 # define CRYPTO_LOCK 1 # define GEN_DNS 2 # define GEN_IPADD 7 # define NID_commonName 13 # define NID_subject_alt_name 85 # define SSL_VERIFY_NONE 0x00 # define SSL_CTRL_OPTIONS 32 # define SSL_CTRL_MODE 33 # define SSL_CTRL_SET_TLSEXT_HOSTNAME 55 # define SSL_ERROR_NONE 0 # define SSL_ERROR_SSL 1 # define SSL_ERROR_WANT_READ 2 # define SSL_ERROR_WANT_WRITE 3 # define SSL_ERROR_WANT_X509_LOOKUP 4 # define SSL_ERROR_SYSCALL 5 # define SSL_ERROR_ZERO_RETURN 6 # define SSL_ERROR_WANT_CONNECT 7 # define SSL_ERROR_WANT_ACCEPT 8 # define SSL_OP_NO_COMPRESSION 0x00020000L # define SSL_OP_NO_SSLv2 0x01000000L # define SSL_OP_NO_SSLv3 0x02000000L # define SSL_MODE_AUTO_RETRY 0x00000004L # define TLSEXT_NAMETYPE_host_name 0 # define V_ASN1_UTF8STRING 12 # define X509_V_OK 0 /* Most of the OpenSSL types are mercifully opaque, so we can treat them like `void *` */ typedef struct bio_st BIO; typedef struct bio_method_st BIO_METHOD; typedef void bio_info_cb; typedef void * CRYPTO_EX_DATA; typedef void CRYPTO_THREADID; typedef void GENERAL_NAMES; typedef void SSL; typedef void SSL_CTX; typedef void SSL_METHOD; typedef void X509; typedef void X509_NAME; typedef void X509_NAME_ENTRY; typedef void X509_STORE_CTX; typedef struct { int length; int type; unsigned char *data; long flags; } ASN1_STRING; typedef struct { int type; union { char *ptr; ASN1_STRING *ia5; } d; } GENERAL_NAME; struct bio_st { BIO_METHOD *method; /* bio, mode, argp, argi, argl, ret */ long (*callback) (struct bio_st *, int, const char *, int, long, long); char *cb_arg; /* first argument for the callback */ int init; int shutdown; int flags; /* extra storage */ int retry_reason; int num; void *ptr; struct bio_st *next_bio; /* used by filter BIOs */ struct bio_st *prev_bio; /* used by filter BIOs */ int references; unsigned long num_read; unsigned long num_write; CRYPTO_EX_DATA ex_data; }; struct bio_method_st { int type; const char *name; int (*bwrite) (BIO *, const char *, int); int (*bread) (BIO *, char *, int); int (*bputs) (BIO *, const char *); int (*bgets) (BIO *, char *, int); long (*ctrl) (BIO *, int, long, void *); int (*create) (BIO *); int (*destroy) (BIO *); long (*callback_ctrl) (BIO *, int, bio_info_cb *); }; extern unsigned char *(*ASN1_STRING_data)(ASN1_STRING *x); extern const unsigned char *(*ASN1_STRING_get0_data)(const ASN1_STRING *x); extern int (*ASN1_STRING_length)(const ASN1_STRING *x); extern int (*ASN1_STRING_to_UTF8)(unsigned char **out, const ASN1_STRING *in); extern int (*ASN1_STRING_type)(const ASN1_STRING *x); extern void *(*BIO_get_data)(BIO *a); extern int (*BIO_get_new_index)(void); extern int (*OPENSSL_init_ssl)(uint64_t opts, const void *settings); extern void (*BIO_meth_free)(BIO_METHOD *biom); extern int (*BIO_meth_set_create)(BIO_METHOD *biom, int (*create) (BIO *)); extern int (*BIO_meth_set_ctrl)(BIO_METHOD *biom, long (*ctrl) (BIO *, int, long, void *)); extern int (*BIO_meth_set_destroy)(BIO_METHOD *biom, int (*destroy) (BIO *)); extern int (*BIO_meth_set_gets)(BIO_METHOD *biom, int (*gets) (BIO *, char *, int)); extern int (*BIO_meth_set_puts)(BIO_METHOD *biom, int (*puts) (BIO *, const char *)); extern int (*BIO_meth_set_read)(BIO_METHOD *biom, int (*read) (BIO *, char *, int)); extern int (*BIO_meth_set_write)(BIO_METHOD *biom, int (*write) (BIO *, const char *, int)); extern BIO_METHOD *(*BIO_meth_new)(int type, const char *name); extern BIO *(*BIO_new)(const BIO_METHOD *type); extern void (*BIO_set_data)(BIO *a, void *ptr); extern void (*BIO_set_init)(BIO *a, int init); extern void (*CRYPTO_free)(void *ptr, const char *file, int line); extern void *(*CRYPTO_malloc)(size_t num, const char *file, int line); extern int (*CRYPTO_num_locks)(void); extern void (*CRYPTO_set_locking_callback)(void (*func)(int mode, int type, const char *file, int line)); extern int (*CRYPTO_set_mem_functions)(void *(*m)(size_t bytes), void *(*r)(void *mem, size_t size), void (*f)(void *mem)); extern int (*CRYPTO_THREADID_set_callback)(void (*func)(CRYPTO_THREADID *id)); extern void (*CRYPTO_THREADID_set_numeric)(CRYPTO_THREADID *id, unsigned long val); extern char *(*ERR_error_string)(unsigned long e, char *buf); extern void (*ERR_error_string_n)(unsigned long e, char *buf, size_t len); extern unsigned long (*ERR_get_error)(void); # define OPENSSL_malloc(num) CRYPTO_malloc(num, __FILE__, __LINE__) # define OPENSSL_free(addr) CRYPTO_free(addr, __FILE__, __LINE__) extern int (*SSL_connect)(SSL *ssl); extern long (*SSL_ctrl)(SSL *ssl, int cmd, long arg, void *parg); extern void (*SSL_free)(SSL *ssl); extern int (*SSL_get_error)(SSL *ssl, int ret); extern X509 *(*SSL_get_peer_certificate)(const SSL *ssl); extern long (*SSL_get_verify_result)(const SSL *ssl); extern int (*SSL_library_init)(void); extern void (*SSL_load_error_strings)(void); extern SSL *(*SSL_new)(SSL_CTX *ctx); extern int (*SSL_read)(SSL *ssl, const void *buf, int num); extern void (*SSL_set_bio)(SSL *ssl, BIO *rbio, BIO *wbio); extern int (*SSL_shutdown)(SSL *ssl); extern int (*SSL_write)(SSL *ssl, const void *buf, int num); # define SSL_set_tlsext_host_name(s, name) SSL_ctrl((s), SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name, (char *)(name)); extern long (*SSL_CTX_ctrl)(SSL_CTX *ctx, int cmd, long larg, void *parg); extern void (*SSL_CTX_free)(SSL_CTX *ctx); extern SSL_CTX *(*SSL_CTX_new)(const SSL_METHOD *method); extern int (*SSL_CTX_set_cipher_list)(SSL_CTX *ctx, const char *str); extern int (*SSL_CTX_set_default_verify_paths)(SSL_CTX *ctx); extern long (*SSL_CTX_set_options)(SSL_CTX *ctx, long options); extern void (*SSL_CTX_set_verify)(SSL_CTX *ctx, int mode, int (*verify_callback)(int, X509_STORE_CTX *)); extern int (*SSL_CTX_load_verify_locations)(SSL_CTX *ctx, const char *CAfile, const char *CApath); # define SSL_CTX_set_mode(ctx, mode) SSL_CTX_ctrl((ctx), SSL_CTRL_MODE, (mode), NULL); extern const SSL_METHOD *(*SSLv23_method)(void); extern const SSL_METHOD *(*TLS_method)(void); extern ASN1_STRING *(*X509_NAME_ENTRY_get_data)(const X509_NAME_ENTRY *ne); extern X509_NAME_ENTRY *(*X509_NAME_get_entry)(X509_NAME *name, int loc); extern int (*X509_NAME_get_index_by_NID)(X509_NAME *name, int nid, int lastpos); extern void (*X509_free)(X509 *a); extern void *(*X509_get_ext_d2i)(const X509 *x, int nid, int *crit, int *idx); extern X509_NAME *(*X509_get_subject_name)(const X509 *x); extern int (*i2d_X509)(X509 *a, unsigned char **ppout); extern int (*OPENSSL_sk_num)(const void *sk); extern void *(*OPENSSL_sk_value)(const void *sk, int i); extern void (*OPENSSL_sk_free)(void *sk); extern int (*sk_num)(const void *sk); extern void *(*sk_value)(const void *sk, int i); extern void (*sk_free)(void *sk); extern int sk_GENERAL_NAME_num(const GENERAL_NAME *sk); extern GENERAL_NAME *sk_GENERAL_NAME_value(const GENERAL_NAME *sk, int i); extern void GENERAL_NAMES_free(GENERAL_NAME *sk); extern int git_openssl_stream_dynamic_init(void); #endif /* GIT_OPENSSL_DYNAMIC */ #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/streams/registry.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_streams_registry_h__ #define INCLUDE_streams_registry_h__ #include "common.h" #include "git2/sys/stream.h" /** Configure stream registry. */ int git_stream_registry_global_init(void); /** Lookup a stream registration. */ extern int git_stream_registry_lookup(git_stream_registration *out, git_stream_t type); #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/streams/stransport.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "streams/stransport.h" #ifdef GIT_SECURE_TRANSPORT #include <CoreFoundation/CoreFoundation.h> #include <Security/SecureTransport.h> #include <Security/SecCertificate.h> #include "git2/transport.h" #include "streams/socket.h" static int stransport_error(OSStatus ret) { CFStringRef message; if (ret == noErr || ret == errSSLClosedGraceful) { git_error_clear(); return 0; } #if !TARGET_OS_IPHONE message = SecCopyErrorMessageString(ret, NULL); GIT_ERROR_CHECK_ALLOC(message); git_error_set(GIT_ERROR_NET, "SecureTransport error: %s", CFStringGetCStringPtr(message, kCFStringEncodingUTF8)); CFRelease(message); #else git_error_set(GIT_ERROR_NET, "SecureTransport error: OSStatus %d", (unsigned int)ret); GIT_UNUSED(message); #endif return -1; } typedef struct { git_stream parent; git_stream *io; int owned; SSLContextRef ctx; CFDataRef der_data; git_cert_x509 cert_info; } stransport_stream; static int stransport_connect(git_stream *stream) { stransport_stream *st = (stransport_stream *) stream; int error; SecTrustRef trust = NULL; SecTrustResultType sec_res; OSStatus ret; if (st->owned && (error = git_stream_connect(st->io)) < 0) return error; ret = SSLHandshake(st->ctx); if (ret != errSSLServerAuthCompleted) { git_error_set(GIT_ERROR_SSL, "unexpected return value from ssl handshake %d", (int)ret); return -1; } if ((ret = SSLCopyPeerTrust(st->ctx, &trust)) != noErr) goto on_error; if (!trust) return GIT_ECERTIFICATE; if ((ret = SecTrustEvaluate(trust, &sec_res)) != noErr) goto on_error; CFRelease(trust); if (sec_res == kSecTrustResultInvalid || sec_res == kSecTrustResultOtherError) { git_error_set(GIT_ERROR_SSL, "internal security trust error"); return -1; } if (sec_res == kSecTrustResultDeny || sec_res == kSecTrustResultRecoverableTrustFailure || sec_res == kSecTrustResultFatalTrustFailure) { git_error_set(GIT_ERROR_SSL, "untrusted connection error"); return GIT_ECERTIFICATE; } return 0; on_error: if (trust) CFRelease(trust); return stransport_error(ret); } static int stransport_certificate(git_cert **out, git_stream *stream) { stransport_stream *st = (stransport_stream *) stream; SecTrustRef trust = NULL; SecCertificateRef sec_cert; OSStatus ret; if ((ret = SSLCopyPeerTrust(st->ctx, &trust)) != noErr) return stransport_error(ret); sec_cert = SecTrustGetCertificateAtIndex(trust, 0); st->der_data = SecCertificateCopyData(sec_cert); CFRelease(trust); if (st->der_data == NULL) { git_error_set(GIT_ERROR_SSL, "retrieved invalid certificate data"); return -1; } st->cert_info.parent.cert_type = GIT_CERT_X509; st->cert_info.data = (void *) CFDataGetBytePtr(st->der_data); st->cert_info.len = CFDataGetLength(st->der_data); *out = (git_cert *)&st->cert_info; return 0; } static int stransport_set_proxy( git_stream *stream, const git_proxy_options *proxy_opts) { stransport_stream *st = (stransport_stream *) stream; return git_stream_set_proxy(st->io, proxy_opts); } /* * Contrary to typical network IO callbacks, Secure Transport write callback is * expected to write *all* passed data, not just as much as it can, and any * other case would be considered a failure. * * This behavior is actually not specified in the Apple documentation, but is * required for things to work correctly (and incidentally, that's also how * Apple implements it in its projects at opensource.apple.com). * * Libgit2 streams happen to already have this very behavior so this is just * passthrough. */ static OSStatus write_cb(SSLConnectionRef conn, const void *data, size_t *len) { git_stream *io = (git_stream *) conn; if (git_stream__write_full(io, data, *len, 0) < 0) return -36; /* "ioErr" from MacErrors.h which is not available on iOS */ return noErr; } static ssize_t stransport_write(git_stream *stream, const char *data, size_t len, int flags) { stransport_stream *st = (stransport_stream *) stream; size_t data_len, processed; OSStatus ret; GIT_UNUSED(flags); data_len = min(len, SSIZE_MAX); if ((ret = SSLWrite(st->ctx, data, data_len, &processed)) != noErr) return stransport_error(ret); GIT_ASSERT(processed < SSIZE_MAX); return (ssize_t)processed; } /* * Contrary to typical network IO callbacks, Secure Transport read callback is * expected to read *exactly* the requested number of bytes, not just as much * as it can, and any other case would be considered a failure. * * This behavior is actually not specified in the Apple documentation, but is * required for things to work correctly (and incidentally, that's also how * Apple implements it in its projects at opensource.apple.com). */ static OSStatus read_cb(SSLConnectionRef conn, void *data, size_t *len) { git_stream *io = (git_stream *) conn; OSStatus error = noErr; size_t off = 0; ssize_t ret; do { ret = git_stream_read(io, data + off, *len - off); if (ret < 0) { error = -36; /* "ioErr" from MacErrors.h which is not available on iOS */ break; } if (ret == 0) { error = errSSLClosedGraceful; break; } off += ret; } while (off < *len); *len = off; return error; } static ssize_t stransport_read(git_stream *stream, void *data, size_t len) { stransport_stream *st = (stransport_stream *) stream; size_t processed; OSStatus ret; if ((ret = SSLRead(st->ctx, data, len, &processed)) != noErr) return stransport_error(ret); return processed; } static int stransport_close(git_stream *stream) { stransport_stream *st = (stransport_stream *) stream; OSStatus ret; ret = SSLClose(st->ctx); if (ret != noErr && ret != errSSLClosedGraceful) return stransport_error(ret); return st->owned ? git_stream_close(st->io) : 0; } static void stransport_free(git_stream *stream) { stransport_stream *st = (stransport_stream *) stream; if (st->owned) git_stream_free(st->io); CFRelease(st->ctx); if (st->der_data) CFRelease(st->der_data); git__free(st); } static int stransport_wrap( git_stream **out, git_stream *in, const char *host, int owned) { stransport_stream *st; OSStatus ret; GIT_ASSERT_ARG(out); GIT_ASSERT_ARG(in); GIT_ASSERT_ARG(host); st = git__calloc(1, sizeof(stransport_stream)); GIT_ERROR_CHECK_ALLOC(st); st->io = in; st->owned = owned; st->ctx = SSLCreateContext(NULL, kSSLClientSide, kSSLStreamType); if (!st->ctx) { git_error_set(GIT_ERROR_NET, "failed to create SSL context"); git__free(st); return -1; } if ((ret = SSLSetIOFuncs(st->ctx, read_cb, write_cb)) != noErr || (ret = SSLSetConnection(st->ctx, st->io)) != noErr || (ret = SSLSetSessionOption(st->ctx, kSSLSessionOptionBreakOnServerAuth, true)) != noErr || (ret = SSLSetProtocolVersionMin(st->ctx, kTLSProtocol1)) != noErr || (ret = SSLSetProtocolVersionMax(st->ctx, kTLSProtocol12)) != noErr || (ret = SSLSetPeerDomainName(st->ctx, host, strlen(host))) != noErr) { CFRelease(st->ctx); git__free(st); return stransport_error(ret); } st->parent.version = GIT_STREAM_VERSION; st->parent.encrypted = 1; st->parent.proxy_support = git_stream_supports_proxy(st->io); st->parent.connect = stransport_connect; st->parent.certificate = stransport_certificate; st->parent.set_proxy = stransport_set_proxy; st->parent.read = stransport_read; st->parent.write = stransport_write; st->parent.close = stransport_close; st->parent.free = stransport_free; *out = (git_stream *) st; return 0; } int git_stransport_stream_wrap( git_stream **out, git_stream *in, const char *host) { return stransport_wrap(out, in, host, 0); } int git_stransport_stream_new(git_stream **out, const char *host, const char *port) { git_stream *stream = NULL; int error; GIT_ASSERT_ARG(out); GIT_ASSERT_ARG(host); error = git_socket_stream_new(&stream, host, port); if (!error) error = stransport_wrap(out, stream, host, 1); if (error < 0 && stream) { git_stream_close(stream); git_stream_free(stream); } return error; } #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/streams/mbedtls.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "streams/mbedtls.h" #ifdef GIT_MBEDTLS #include <ctype.h> #include "runtime.h" #include "stream.h" #include "streams/socket.h" #include "netops.h" #include "git2/transport.h" #include "util.h" #ifndef GIT_DEFAULT_CERT_LOCATION #define GIT_DEFAULT_CERT_LOCATION NULL #endif /* Work around C90-conformance issues */ #if defined(_MSC_VER) # define inline __inline #elif defined(__GNUC__) # define inline __inline__ #else # define inline #endif #include <mbedtls/config.h> #include <mbedtls/ssl.h> #include <mbedtls/error.h> #include <mbedtls/entropy.h> #include <mbedtls/ctr_drbg.h> #undef inline #define GIT_SSL_DEFAULT_CIPHERS "TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256:TLS-ECDHE-RSA-WITH-AES-128-GCM-SHA256:TLS-ECDHE-ECDSA-WITH-AES-256-GCM-SHA384:TLS-ECDHE-RSA-WITH-AES-256-GCM-SHA384:TLS-DHE-RSA-WITH-AES-128-GCM-SHA256:TLS-DHE-DSS-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-256-GCM-SHA384:TLS-DHE-DSS-WITH-AES-256-GCM-SHA384:TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA256:TLS-ECDHE-RSA-WITH-AES-128-CBC-SHA256:TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA:TLS-ECDHE-RSA-WITH-AES-128-CBC-SHA:TLS-ECDHE-ECDSA-WITH-AES-256-CBC-SHA384:TLS-ECDHE-RSA-WITH-AES-256-CBC-SHA384:TLS-ECDHE-ECDSA-WITH-AES-256-CBC-SHA:TLS-ECDHE-RSA-WITH-AES-256-CBC-SHA:TLS-DHE-RSA-WITH-AES-128-CBC-SHA256:TLS-DHE-RSA-WITH-AES-256-CBC-SHA256:TLS-DHE-RSA-WITH-AES-128-CBC-SHA:TLS-DHE-RSA-WITH-AES-256-CBC-SHA:TLS-DHE-DSS-WITH-AES-128-CBC-SHA256:TLS-DHE-DSS-WITH-AES-256-CBC-SHA256:TLS-DHE-DSS-WITH-AES-128-CBC-SHA:TLS-DHE-DSS-WITH-AES-256-CBC-SHA:TLS-RSA-WITH-AES-128-GCM-SHA256:TLS-RSA-WITH-AES-256-GCM-SHA384:TLS-RSA-WITH-AES-128-CBC-SHA256:TLS-RSA-WITH-AES-256-CBC-SHA256:TLS-RSA-WITH-AES-128-CBC-SHA:TLS-RSA-WITH-AES-256-CBC-SHA" #define GIT_SSL_DEFAULT_CIPHERS_COUNT 30 static mbedtls_ssl_config *git__ssl_conf; static int ciphers_list[GIT_SSL_DEFAULT_CIPHERS_COUNT]; static mbedtls_entropy_context *mbedtls_entropy; /** * This function aims to clean-up the SSL context which * we allocated. */ static void shutdown_ssl(void) { if (git__ssl_conf) { mbedtls_x509_crt_free(git__ssl_conf->ca_chain); git__free(git__ssl_conf->ca_chain); mbedtls_ctr_drbg_free(git__ssl_conf->p_rng); git__free(git__ssl_conf->p_rng); mbedtls_ssl_config_free(git__ssl_conf); git__free(git__ssl_conf); git__ssl_conf = NULL; } if (mbedtls_entropy) { mbedtls_entropy_free(mbedtls_entropy); git__free(mbedtls_entropy); mbedtls_entropy = NULL; } } int git_mbedtls_stream_global_init(void) { int loaded = 0; char *crtpath = GIT_DEFAULT_CERT_LOCATION; struct stat statbuf; mbedtls_ctr_drbg_context *ctr_drbg = NULL; size_t ciphers_known = 0; char *cipher_name = NULL; char *cipher_string = NULL; char *cipher_string_tmp = NULL; git__ssl_conf = git__malloc(sizeof(mbedtls_ssl_config)); GIT_ERROR_CHECK_ALLOC(git__ssl_conf); mbedtls_ssl_config_init(git__ssl_conf); if (mbedtls_ssl_config_defaults(git__ssl_conf, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) != 0) { git_error_set(GIT_ERROR_SSL, "failed to initialize mbedTLS"); goto cleanup; } /* configure TLSv1 */ mbedtls_ssl_conf_min_version(git__ssl_conf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0); /* verify_server_cert is responsible for making the check. * OPTIONAL because REQUIRED drops the certificate as soon as the check * is made, so we can never see the certificate and override it. */ mbedtls_ssl_conf_authmode(git__ssl_conf, MBEDTLS_SSL_VERIFY_OPTIONAL); /* set the list of allowed ciphersuites */ ciphers_known = 0; cipher_string = cipher_string_tmp = git__strdup(GIT_SSL_DEFAULT_CIPHERS); GIT_ERROR_CHECK_ALLOC(cipher_string); while ((cipher_name = git__strtok(&cipher_string_tmp, ":")) != NULL) { int cipherid = mbedtls_ssl_get_ciphersuite_id(cipher_name); if (cipherid == 0) continue; if (ciphers_known >= ARRAY_SIZE(ciphers_list)) { git_error_set(GIT_ERROR_SSL, "out of cipher list space"); goto cleanup; } ciphers_list[ciphers_known++] = cipherid; } git__free(cipher_string); if (!ciphers_known) { git_error_set(GIT_ERROR_SSL, "no cipher could be enabled"); goto cleanup; } mbedtls_ssl_conf_ciphersuites(git__ssl_conf, ciphers_list); /* Seeding the random number generator */ mbedtls_entropy = git__malloc(sizeof(mbedtls_entropy_context)); GIT_ERROR_CHECK_ALLOC(mbedtls_entropy); mbedtls_entropy_init(mbedtls_entropy); ctr_drbg = git__malloc(sizeof(mbedtls_ctr_drbg_context)); GIT_ERROR_CHECK_ALLOC(ctr_drbg); mbedtls_ctr_drbg_init(ctr_drbg); if (mbedtls_ctr_drbg_seed(ctr_drbg, mbedtls_entropy_func, mbedtls_entropy, NULL, 0) != 0) { git_error_set(GIT_ERROR_SSL, "failed to initialize mbedTLS entropy pool"); goto cleanup; } mbedtls_ssl_conf_rng(git__ssl_conf, mbedtls_ctr_drbg_random, ctr_drbg); /* load default certificates */ if (crtpath != NULL && stat(crtpath, &statbuf) == 0 && S_ISREG(statbuf.st_mode)) loaded = (git_mbedtls__set_cert_location(crtpath, NULL) == 0); if (!loaded && crtpath != NULL && stat(crtpath, &statbuf) == 0 && S_ISDIR(statbuf.st_mode)) loaded = (git_mbedtls__set_cert_location(NULL, crtpath) == 0); return git_runtime_shutdown_register(shutdown_ssl); cleanup: mbedtls_ctr_drbg_free(ctr_drbg); git__free(ctr_drbg); mbedtls_ssl_config_free(git__ssl_conf); git__free(git__ssl_conf); git__ssl_conf = NULL; return -1; } static int bio_read(void *b, unsigned char *buf, size_t len) { git_stream *io = (git_stream *) b; return (int) git_stream_read(io, buf, min(len, INT_MAX)); } static int bio_write(void *b, const unsigned char *buf, size_t len) { git_stream *io = (git_stream *) b; return (int) git_stream_write(io, (const char *)buf, min(len, INT_MAX), 0); } static int ssl_set_error(mbedtls_ssl_context *ssl, int error) { char errbuf[512]; int ret = -1; GIT_ASSERT(error != MBEDTLS_ERR_SSL_WANT_READ); GIT_ASSERT(error != MBEDTLS_ERR_SSL_WANT_WRITE); if (error != 0) mbedtls_strerror( error, errbuf, 512 ); switch(error) { case 0: git_error_set(GIT_ERROR_SSL, "SSL error: unknown error"); break; case MBEDTLS_ERR_X509_CERT_VERIFY_FAILED: git_error_set(GIT_ERROR_SSL, "SSL error: %#04x [%x] - %s", error, ssl->session_negotiate->verify_result, errbuf); ret = GIT_ECERTIFICATE; break; default: git_error_set(GIT_ERROR_SSL, "SSL error: %#04x - %s", error, errbuf); } return ret; } static int ssl_teardown(mbedtls_ssl_context *ssl) { int ret = 0; ret = mbedtls_ssl_close_notify(ssl); if (ret < 0) ret = ssl_set_error(ssl, ret); mbedtls_ssl_free(ssl); return ret; } static int verify_server_cert(mbedtls_ssl_context *ssl) { int ret = -1; if ((ret = mbedtls_ssl_get_verify_result(ssl)) != 0) { char vrfy_buf[512]; int len = mbedtls_x509_crt_verify_info(vrfy_buf, sizeof(vrfy_buf), "", ret); if (len >= 1) vrfy_buf[len - 1] = '\0'; /* Remove trailing \n */ git_error_set(GIT_ERROR_SSL, "the SSL certificate is invalid: %#04x - %s", ret, vrfy_buf); return GIT_ECERTIFICATE; } return 0; } typedef struct { git_stream parent; git_stream *io; int owned; bool connected; char *host; mbedtls_ssl_context *ssl; git_cert_x509 cert_info; } mbedtls_stream; static int mbedtls_connect(git_stream *stream) { int ret; mbedtls_stream *st = (mbedtls_stream *) stream; if (st->owned && (ret = git_stream_connect(st->io)) < 0) return ret; st->connected = true; mbedtls_ssl_set_hostname(st->ssl, st->host); mbedtls_ssl_set_bio(st->ssl, st->io, bio_write, bio_read, NULL); if ((ret = mbedtls_ssl_handshake(st->ssl)) != 0) return ssl_set_error(st->ssl, ret); return verify_server_cert(st->ssl); } static int mbedtls_certificate(git_cert **out, git_stream *stream) { unsigned char *encoded_cert; mbedtls_stream *st = (mbedtls_stream *) stream; const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(st->ssl); if (!cert) { git_error_set(GIT_ERROR_SSL, "the server did not provide a certificate"); return -1; } /* Retrieve the length of the certificate first */ if (cert->raw.len == 0) { git_error_set(GIT_ERROR_NET, "failed to retrieve certificate information"); return -1; } encoded_cert = git__malloc(cert->raw.len); GIT_ERROR_CHECK_ALLOC(encoded_cert); memcpy(encoded_cert, cert->raw.p, cert->raw.len); st->cert_info.parent.cert_type = GIT_CERT_X509; st->cert_info.data = encoded_cert; st->cert_info.len = cert->raw.len; *out = &st->cert_info.parent; return 0; } static int mbedtls_set_proxy(git_stream *stream, const git_proxy_options *proxy_options) { mbedtls_stream *st = (mbedtls_stream *) stream; return git_stream_set_proxy(st->io, proxy_options); } static ssize_t mbedtls_stream_write(git_stream *stream, const char *data, size_t len, int flags) { mbedtls_stream *st = (mbedtls_stream *) stream; int written; GIT_UNUSED(flags); /* * `mbedtls_ssl_write` can only represent INT_MAX bytes * written via its return value. We thus need to clamp * the maximum number of bytes written. */ len = min(len, INT_MAX); if ((written = mbedtls_ssl_write(st->ssl, (const unsigned char *)data, len)) <= 0) return ssl_set_error(st->ssl, written); return written; } static ssize_t mbedtls_stream_read(git_stream *stream, void *data, size_t len) { mbedtls_stream *st = (mbedtls_stream *) stream; int ret; if ((ret = mbedtls_ssl_read(st->ssl, (unsigned char *)data, len)) <= 0) ssl_set_error(st->ssl, ret); return ret; } static int mbedtls_stream_close(git_stream *stream) { mbedtls_stream *st = (mbedtls_stream *) stream; int ret = 0; if (st->connected && (ret = ssl_teardown(st->ssl)) != 0) return -1; st->connected = false; return st->owned ? git_stream_close(st->io) : 0; } static void mbedtls_stream_free(git_stream *stream) { mbedtls_stream *st = (mbedtls_stream *) stream; if (st->owned) git_stream_free(st->io); git__free(st->host); git__free(st->cert_info.data); mbedtls_ssl_free(st->ssl); git__free(st->ssl); git__free(st); } static int mbedtls_stream_wrap( git_stream **out, git_stream *in, const char *host, int owned) { mbedtls_stream *st; int error; st = git__calloc(1, sizeof(mbedtls_stream)); GIT_ERROR_CHECK_ALLOC(st); st->io = in; st->owned = owned; st->ssl = git__malloc(sizeof(mbedtls_ssl_context)); GIT_ERROR_CHECK_ALLOC(st->ssl); mbedtls_ssl_init(st->ssl); if (mbedtls_ssl_setup(st->ssl, git__ssl_conf)) { git_error_set(GIT_ERROR_SSL, "failed to create ssl object"); error = -1; goto out_err; } st->host = git__strdup(host); GIT_ERROR_CHECK_ALLOC(st->host); st->parent.version = GIT_STREAM_VERSION; st->parent.encrypted = 1; st->parent.proxy_support = git_stream_supports_proxy(st->io); st->parent.connect = mbedtls_connect; st->parent.certificate = mbedtls_certificate; st->parent.set_proxy = mbedtls_set_proxy; st->parent.read = mbedtls_stream_read; st->parent.write = mbedtls_stream_write; st->parent.close = mbedtls_stream_close; st->parent.free = mbedtls_stream_free; *out = (git_stream *) st; return 0; out_err: mbedtls_ssl_free(st->ssl); git_stream_close(st->io); git_stream_free(st->io); git__free(st); return error; } int git_mbedtls_stream_wrap( git_stream **out, git_stream *in, const char *host) { return mbedtls_stream_wrap(out, in, host, 0); } int git_mbedtls_stream_new( git_stream **out, const char *host, const char *port) { git_stream *stream; int error; GIT_ASSERT_ARG(out); GIT_ASSERT_ARG(host); GIT_ASSERT_ARG(port); if ((error = git_socket_stream_new(&stream, host, port)) < 0) return error; if ((error = mbedtls_stream_wrap(out, stream, host, 1)) < 0) { git_stream_close(stream); git_stream_free(stream); } return error; } int git_mbedtls__set_cert_location(const char *file, const char *path) { int ret = 0; char errbuf[512]; mbedtls_x509_crt *cacert; GIT_ASSERT_ARG(file || path); cacert = git__malloc(sizeof(mbedtls_x509_crt)); GIT_ERROR_CHECK_ALLOC(cacert); mbedtls_x509_crt_init(cacert); if (file) ret = mbedtls_x509_crt_parse_file(cacert, file); if (ret >= 0 && path) ret = mbedtls_x509_crt_parse_path(cacert, path); /* mbedtls_x509_crt_parse_path returns the number of invalid certs on success */ if (ret < 0) { mbedtls_x509_crt_free(cacert); git__free(cacert); mbedtls_strerror( ret, errbuf, 512 ); git_error_set(GIT_ERROR_SSL, "failed to load CA certificates: %#04x - %s", ret, errbuf); return -1; } mbedtls_x509_crt_free(git__ssl_conf->ca_chain); git__free(git__ssl_conf->ca_chain); mbedtls_ssl_conf_ca_chain(git__ssl_conf, cacert, NULL); return 0; } #else #include "stream.h" int git_mbedtls_stream_global_init(void) { return 0; } #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/streams/mbedtls.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_steams_mbedtls_h__ #define INCLUDE_steams_mbedtls_h__ #include "common.h" #include "git2/sys/stream.h" extern int git_mbedtls_stream_global_init(void); #ifdef GIT_MBEDTLS extern int git_mbedtls__set_cert_location(const char *file, const char *path); extern int git_mbedtls_stream_new(git_stream **out, const char *host, const char *port); extern int git_mbedtls_stream_wrap(git_stream **out, git_stream *in, const char *host); #endif #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash/sha1.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_hash_sha1_h__ #define INCLUDE_hash_sha1_h__ #include "common.h" typedef struct git_hash_sha1_ctx git_hash_sha1_ctx; #if defined(GIT_SHA1_COLLISIONDETECT) # include "sha1/collisiondetect.h" #elif defined(GIT_SHA1_COMMON_CRYPTO) # include "sha1/common_crypto.h" #elif defined(GIT_SHA1_OPENSSL) # include "sha1/openssl.h" #elif defined(GIT_SHA1_WIN32) # include "sha1/win32.h" #elif defined(GIT_SHA1_MBEDTLS) # include "sha1/mbedtls.h" #else # include "sha1/generic.h" #endif int git_hash_sha1_global_init(void); int git_hash_sha1_ctx_init(git_hash_sha1_ctx *ctx); void git_hash_sha1_ctx_cleanup(git_hash_sha1_ctx *ctx); int git_hash_sha1_init(git_hash_sha1_ctx *c); int git_hash_sha1_update(git_hash_sha1_ctx *c, const void *data, size_t len); int git_hash_sha1_final(git_oid *out, git_hash_sha1_ctx *c); #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash/sha1/common_crypto.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_hash_sha1_common_crypto_h__ #define INCLUDE_hash_sha1_common_crypto_h__ #include "hash/sha1.h" #include <CommonCrypto/CommonDigest.h> struct git_hash_sha1_ctx { CC_SHA1_CTX c; }; #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash/sha1/openssl.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_hash_sha1_openssl_h__ #define INCLUDE_hash_sha1_openssl_h__ #include "hash/sha1.h" #include <openssl/sha.h> struct git_hash_sha1_ctx { SHA_CTX c; }; #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash/sha1/collisiondetect.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "collisiondetect.h" int git_hash_sha1_global_init(void) { return 0; } int git_hash_sha1_ctx_init(git_hash_sha1_ctx *ctx) { return git_hash_sha1_init(ctx); } void git_hash_sha1_ctx_cleanup(git_hash_sha1_ctx *ctx) { GIT_UNUSED(ctx); } int git_hash_sha1_init(git_hash_sha1_ctx *ctx) { GIT_ASSERT_ARG(ctx); SHA1DCInit(&ctx->c); return 0; } int git_hash_sha1_update(git_hash_sha1_ctx *ctx, const void *data, size_t len) { GIT_ASSERT_ARG(ctx); SHA1DCUpdate(&ctx->c, data, len); return 0; } int git_hash_sha1_final(git_oid *out, git_hash_sha1_ctx *ctx) { GIT_ASSERT_ARG(ctx); if (SHA1DCFinal(out->id, &ctx->c)) { git_error_set(GIT_ERROR_SHA1, "SHA1 collision attack detected"); return -1; } return 0; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash/sha1/generic.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_hash_sha1_generic_h__ #define INCLUDE_hash_sha1_generic_h__ #include "hash/sha1.h" struct git_hash_sha1_ctx { uint64_t size; unsigned int H[5]; unsigned int W[16]; }; #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash/sha1/collisiondetect.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_hash_sha1_collisiondetect_h__ #define INCLUDE_hash_sha1_collisiondetect_h__ #include "hash/sha1.h" #include "sha1dc/sha1.h" struct git_hash_sha1_ctx { SHA1_CTX c; }; #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash/sha1/generic.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "generic.h" #if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) /* * Force usage of rol or ror by selecting the one with the smaller constant. * It _can_ generate slightly smaller code (a constant of 1 is special), but * perhaps more importantly it's possibly faster on any uarch that does a * rotate with a loop. */ #define SHA_ASM(op, x, n) (__extension__ ({ unsigned int __res; __asm__(op " %1,%0":"=r" (__res):"i" (n), "0" (x)); __res; })) #define SHA_ROL(x,n) SHA_ASM("rol", x, n) #define SHA_ROR(x,n) SHA_ASM("ror", x, n) #else #define SHA_ROT(X,l,r) (((X) << (l)) | ((X) >> (r))) #define SHA_ROL(X,n) SHA_ROT(X,n,32-(n)) #define SHA_ROR(X,n) SHA_ROT(X,32-(n),n) #endif /* * If you have 32 registers or more, the compiler can (and should) * try to change the array[] accesses into registers. However, on * machines with less than ~25 registers, that won't really work, * and at least gcc will make an unholy mess of it. * * So to avoid that mess which just slows things down, we force * the stores to memory to actually happen (we might be better off * with a 'W(t)=(val);asm("":"+m" (W(t))' there instead, as * suggested by Artur Skawina - that will also make gcc unable to * try to do the silly "optimize away loads" part because it won't * see what the value will be). * * Ben Herrenschmidt reports that on PPC, the C version comes close * to the optimized asm with this (ie on PPC you don't want that * 'volatile', since there are lots of registers). * * On ARM we get the best code generation by forcing a full memory barrier * between each SHA_ROUND, otherwise gcc happily get wild with spilling and * the stack frame size simply explode and performance goes down the drain. */ #if defined(__i386__) || defined(__x86_64__) #define setW(x, val) (*(volatile unsigned int *)&W(x) = (val)) #elif defined(__GNUC__) && defined(__arm__) #define setW(x, val) do { W(x) = (val); __asm__("":::"memory"); } while (0) #else #define setW(x, val) (W(x) = (val)) #endif /* * Performance might be improved if the CPU architecture is OK with * unaligned 32-bit loads and a fast ntohl() is available. * Otherwise fall back to byte loads and shifts which is portable, * and is faster on architectures with memory alignment issues. */ #if defined(__i386__) || defined(__x86_64__) || \ defined(_M_IX86) || defined(_M_X64) || \ defined(__ppc__) || defined(__ppc64__) || \ defined(__powerpc__) || defined(__powerpc64__) || \ defined(__s390__) || defined(__s390x__) #define get_be32(p) ntohl(*(const unsigned int *)(p)) #define put_be32(p, v) do { *(unsigned int *)(p) = htonl(v); } while (0) #else #define get_be32(p) ( \ (*((const unsigned char *)(p) + 0) << 24) | \ (*((const unsigned char *)(p) + 1) << 16) | \ (*((const unsigned char *)(p) + 2) << 8) | \ (*((const unsigned char *)(p) + 3) << 0) ) #define put_be32(p, v) do { \ unsigned int __v = (v); \ *((unsigned char *)(p) + 0) = __v >> 24; \ *((unsigned char *)(p) + 1) = __v >> 16; \ *((unsigned char *)(p) + 2) = __v >> 8; \ *((unsigned char *)(p) + 3) = __v >> 0; } while (0) #endif /* This "rolls" over the 512-bit array */ #define W(x) (array[(x)&15]) /* * Where do we get the source from? The first 16 iterations get it from * the input data, the next mix it from the 512-bit array. */ #define SHA_SRC(t) get_be32(data + t) #define SHA_MIX(t) SHA_ROL(W(t+13) ^ W(t+8) ^ W(t+2) ^ W(t), 1) #define SHA_ROUND(t, input, fn, constant, A, B, C, D, E) do { \ unsigned int TEMP = input(t); setW(t, TEMP); \ E += TEMP + SHA_ROL(A,5) + (fn) + (constant); \ B = SHA_ROR(B, 2); } while (0) #define T_0_15(t, A, B, C, D, E) SHA_ROUND(t, SHA_SRC, (((C^D)&B)^D) , 0x5a827999, A, B, C, D, E ) #define T_16_19(t, A, B, C, D, E) SHA_ROUND(t, SHA_MIX, (((C^D)&B)^D) , 0x5a827999, A, B, C, D, E ) #define T_20_39(t, A, B, C, D, E) SHA_ROUND(t, SHA_MIX, (B^C^D) , 0x6ed9eba1, A, B, C, D, E ) #define T_40_59(t, A, B, C, D, E) SHA_ROUND(t, SHA_MIX, ((B&C)+(D&(B^C))) , 0x8f1bbcdc, A, B, C, D, E ) #define T_60_79(t, A, B, C, D, E) SHA_ROUND(t, SHA_MIX, (B^C^D) , 0xca62c1d6, A, B, C, D, E ) static void hash__block(git_hash_sha1_ctx *ctx, const unsigned int *data) { unsigned int A,B,C,D,E; unsigned int array[16]; A = ctx->H[0]; B = ctx->H[1]; C = ctx->H[2]; D = ctx->H[3]; E = ctx->H[4]; /* Round 1 - iterations 0-16 take their input from 'data' */ T_0_15( 0, A, B, C, D, E); T_0_15( 1, E, A, B, C, D); T_0_15( 2, D, E, A, B, C); T_0_15( 3, C, D, E, A, B); T_0_15( 4, B, C, D, E, A); T_0_15( 5, A, B, C, D, E); T_0_15( 6, E, A, B, C, D); T_0_15( 7, D, E, A, B, C); T_0_15( 8, C, D, E, A, B); T_0_15( 9, B, C, D, E, A); T_0_15(10, A, B, C, D, E); T_0_15(11, E, A, B, C, D); T_0_15(12, D, E, A, B, C); T_0_15(13, C, D, E, A, B); T_0_15(14, B, C, D, E, A); T_0_15(15, A, B, C, D, E); /* Round 1 - tail. Input from 512-bit mixing array */ T_16_19(16, E, A, B, C, D); T_16_19(17, D, E, A, B, C); T_16_19(18, C, D, E, A, B); T_16_19(19, B, C, D, E, A); /* Round 2 */ T_20_39(20, A, B, C, D, E); T_20_39(21, E, A, B, C, D); T_20_39(22, D, E, A, B, C); T_20_39(23, C, D, E, A, B); T_20_39(24, B, C, D, E, A); T_20_39(25, A, B, C, D, E); T_20_39(26, E, A, B, C, D); T_20_39(27, D, E, A, B, C); T_20_39(28, C, D, E, A, B); T_20_39(29, B, C, D, E, A); T_20_39(30, A, B, C, D, E); T_20_39(31, E, A, B, C, D); T_20_39(32, D, E, A, B, C); T_20_39(33, C, D, E, A, B); T_20_39(34, B, C, D, E, A); T_20_39(35, A, B, C, D, E); T_20_39(36, E, A, B, C, D); T_20_39(37, D, E, A, B, C); T_20_39(38, C, D, E, A, B); T_20_39(39, B, C, D, E, A); /* Round 3 */ T_40_59(40, A, B, C, D, E); T_40_59(41, E, A, B, C, D); T_40_59(42, D, E, A, B, C); T_40_59(43, C, D, E, A, B); T_40_59(44, B, C, D, E, A); T_40_59(45, A, B, C, D, E); T_40_59(46, E, A, B, C, D); T_40_59(47, D, E, A, B, C); T_40_59(48, C, D, E, A, B); T_40_59(49, B, C, D, E, A); T_40_59(50, A, B, C, D, E); T_40_59(51, E, A, B, C, D); T_40_59(52, D, E, A, B, C); T_40_59(53, C, D, E, A, B); T_40_59(54, B, C, D, E, A); T_40_59(55, A, B, C, D, E); T_40_59(56, E, A, B, C, D); T_40_59(57, D, E, A, B, C); T_40_59(58, C, D, E, A, B); T_40_59(59, B, C, D, E, A); /* Round 4 */ T_60_79(60, A, B, C, D, E); T_60_79(61, E, A, B, C, D); T_60_79(62, D, E, A, B, C); T_60_79(63, C, D, E, A, B); T_60_79(64, B, C, D, E, A); T_60_79(65, A, B, C, D, E); T_60_79(66, E, A, B, C, D); T_60_79(67, D, E, A, B, C); T_60_79(68, C, D, E, A, B); T_60_79(69, B, C, D, E, A); T_60_79(70, A, B, C, D, E); T_60_79(71, E, A, B, C, D); T_60_79(72, D, E, A, B, C); T_60_79(73, C, D, E, A, B); T_60_79(74, B, C, D, E, A); T_60_79(75, A, B, C, D, E); T_60_79(76, E, A, B, C, D); T_60_79(77, D, E, A, B, C); T_60_79(78, C, D, E, A, B); T_60_79(79, B, C, D, E, A); ctx->H[0] += A; ctx->H[1] += B; ctx->H[2] += C; ctx->H[3] += D; ctx->H[4] += E; } int git_hash_sha1_global_init(void) { return 0; } int git_hash_sha1_ctx_init(git_hash_sha1_ctx *ctx) { return git_hash_sha1_init(ctx); } void git_hash_sha1_ctx_cleanup(git_hash_sha1_ctx *ctx) { GIT_UNUSED(ctx); } int git_hash_sha1_init(git_hash_sha1_ctx *ctx) { ctx->size = 0; /* Initialize H with the magic constants (see FIPS180 for constants) */ ctx->H[0] = 0x67452301; ctx->H[1] = 0xefcdab89; ctx->H[2] = 0x98badcfe; ctx->H[3] = 0x10325476; ctx->H[4] = 0xc3d2e1f0; return 0; } int git_hash_sha1_update(git_hash_sha1_ctx *ctx, const void *data, size_t len) { unsigned int lenW = ctx->size & 63; ctx->size += len; /* Read the data into W and process blocks as they get full */ if (lenW) { unsigned int left = 64 - lenW; if (len < left) left = (unsigned int)len; memcpy(lenW + (char *)ctx->W, data, left); lenW = (lenW + left) & 63; len -= left; data = ((const char *)data + left); if (lenW) return 0; hash__block(ctx, ctx->W); } while (len >= 64) { hash__block(ctx, data); data = ((const char *)data + 64); len -= 64; } if (len) memcpy(ctx->W, data, len); return 0; } int git_hash_sha1_final(git_oid *out, git_hash_sha1_ctx *ctx) { static const unsigned char pad[64] = { 0x80 }; unsigned int padlen[2]; int i; /* Pad with a binary 1 (ie 0x80), then zeroes, then length */ padlen[0] = htonl((uint32_t)(ctx->size >> 29)); padlen[1] = htonl((uint32_t)(ctx->size << 3)); i = ctx->size & 63; git_hash_sha1_update(ctx, pad, 1+ (63 & (55 - i))); git_hash_sha1_update(ctx, padlen, 8); /* Output hash */ for (i = 0; i < 5; i++) put_be32(out->id + i*4, ctx->H[i]); return 0; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash/sha1/openssl.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "openssl.h" int git_hash_sha1_global_init(void) { return 0; } int git_hash_sha1_ctx_init(git_hash_sha1_ctx *ctx) { return git_hash_sha1_init(ctx); } void git_hash_sha1_ctx_cleanup(git_hash_sha1_ctx *ctx) { GIT_UNUSED(ctx); } int git_hash_sha1_init(git_hash_sha1_ctx *ctx) { GIT_ASSERT_ARG(ctx); if (SHA1_Init(&ctx->c) != 1) { git_error_set(GIT_ERROR_SHA1, "hash_openssl: failed to initialize hash context"); return -1; } return 0; } int git_hash_sha1_update(git_hash_sha1_ctx *ctx, const void *data, size_t len) { GIT_ASSERT_ARG(ctx); if (SHA1_Update(&ctx->c, data, len) != 1) { git_error_set(GIT_ERROR_SHA1, "hash_openssl: failed to update hash"); return -1; } return 0; } int git_hash_sha1_final(git_oid *out, git_hash_sha1_ctx *ctx) { GIT_ASSERT_ARG(ctx); if (SHA1_Final(out->id, &ctx->c) != 1) { git_error_set(GIT_ERROR_SHA1, "hash_openssl: failed to finalize hash"); return -1; } return 0; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash/sha1/win32.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_hash_sha1_win32_h__ #define INCLUDE_hash_sha1_win32_h__ #include "hash/sha1.h" #include <wincrypt.h> #include <strsafe.h> enum hash_win32_prov_type { INVALID = 0, CRYPTOAPI, CNG }; /* * CryptoAPI is available for hashing on Windows XP and newer. */ struct hash_cryptoapi_prov { HCRYPTPROV handle; }; /* * CNG (bcrypt.dll) is significantly more performant than CryptoAPI and is * preferred, however it is only available on Windows 2008 and newer and * must therefore be dynamically loaded, and we must inline constants that * would not exist when building in pre-Windows 2008 environments. */ /* Function declarations for CNG */ typedef NTSTATUS (WINAPI *hash_win32_cng_open_algorithm_provider_fn)( HANDLE /* BCRYPT_ALG_HANDLE */ *phAlgorithm, LPCWSTR pszAlgId, LPCWSTR pszImplementation, DWORD dwFlags); typedef NTSTATUS (WINAPI *hash_win32_cng_get_property_fn)( HANDLE /* BCRYPT_HANDLE */ hObject, LPCWSTR pszProperty, PUCHAR pbOutput, ULONG cbOutput, ULONG *pcbResult, ULONG dwFlags); typedef NTSTATUS (WINAPI *hash_win32_cng_create_hash_fn)( HANDLE /* BCRYPT_ALG_HANDLE */ hAlgorithm, HANDLE /* BCRYPT_HASH_HANDLE */ *phHash, PUCHAR pbHashObject, ULONG cbHashObject, PUCHAR pbSecret, ULONG cbSecret, ULONG dwFlags); typedef NTSTATUS (WINAPI *hash_win32_cng_finish_hash_fn)( HANDLE /* BCRYPT_HASH_HANDLE */ hHash, PUCHAR pbOutput, ULONG cbOutput, ULONG dwFlags); typedef NTSTATUS (WINAPI *hash_win32_cng_hash_data_fn)( HANDLE /* BCRYPT_HASH_HANDLE */ hHash, PUCHAR pbInput, ULONG cbInput, ULONG dwFlags); typedef NTSTATUS (WINAPI *hash_win32_cng_destroy_hash_fn)( HANDLE /* BCRYPT_HASH_HANDLE */ hHash); typedef NTSTATUS (WINAPI *hash_win32_cng_close_algorithm_provider_fn)( HANDLE /* BCRYPT_ALG_HANDLE */ hAlgorithm, ULONG dwFlags); struct hash_cng_prov { /* DLL for CNG */ HINSTANCE dll; /* Function pointers for CNG */ hash_win32_cng_open_algorithm_provider_fn open_algorithm_provider; hash_win32_cng_get_property_fn get_property; hash_win32_cng_create_hash_fn create_hash; hash_win32_cng_finish_hash_fn finish_hash; hash_win32_cng_hash_data_fn hash_data; hash_win32_cng_destroy_hash_fn destroy_hash; hash_win32_cng_close_algorithm_provider_fn close_algorithm_provider; HANDLE /* BCRYPT_ALG_HANDLE */ handle; DWORD hash_object_size; }; typedef struct { enum hash_win32_prov_type type; union { struct hash_cryptoapi_prov cryptoapi; struct hash_cng_prov cng; } prov; } git_hash_prov; /* Hash contexts */ struct hash_cryptoapi_ctx { bool valid; HCRYPTHASH hash_handle; }; struct hash_cng_ctx { bool updated; HANDLE /* BCRYPT_HASH_HANDLE */ hash_handle; PBYTE hash_object; }; struct git_hash_sha1_ctx { enum hash_win32_prov_type type; git_hash_prov *prov; union { struct hash_cryptoapi_ctx cryptoapi; struct hash_cng_ctx cng; } ctx; }; #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash/sha1/win32.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "win32.h" #include "runtime.h" #include <wincrypt.h> #include <strsafe.h> #define GIT_HASH_CNG_DLL_NAME "bcrypt.dll" /* BCRYPT_SHA1_ALGORITHM */ #define GIT_HASH_CNG_HASH_TYPE L"SHA1" /* BCRYPT_OBJECT_LENGTH */ #define GIT_HASH_CNG_HASH_OBJECT_LEN L"ObjectLength" /* BCRYPT_HASH_REUSEABLE_FLAGS */ #define GIT_HASH_CNG_HASH_REUSABLE 0x00000020 static git_hash_prov hash_prov = {0}; /* Hash initialization */ /* Initialize CNG, if available */ GIT_INLINE(int) hash_cng_prov_init(void) { char dll_path[MAX_PATH]; DWORD dll_path_len, size_len; /* Only use CNG on Windows 2008 / Vista SP1 or better (Windows 6.0 SP1) */ if (!git_has_win32_version(6, 0, 1)) { git_error_set(GIT_ERROR_SHA1, "CryptoNG is not supported on this platform"); return -1; } /* Load bcrypt.dll explicitly from the system directory */ if ((dll_path_len = GetSystemDirectory(dll_path, MAX_PATH)) == 0 || dll_path_len > MAX_PATH || StringCchCat(dll_path, MAX_PATH, "\\") < 0 || StringCchCat(dll_path, MAX_PATH, GIT_HASH_CNG_DLL_NAME) < 0 || (hash_prov.prov.cng.dll = LoadLibrary(dll_path)) == NULL) { git_error_set(GIT_ERROR_SHA1, "CryptoNG library could not be loaded"); return -1; } /* Load the function addresses */ if ((hash_prov.prov.cng.open_algorithm_provider = (hash_win32_cng_open_algorithm_provider_fn)GetProcAddress(hash_prov.prov.cng.dll, "BCryptOpenAlgorithmProvider")) == NULL || (hash_prov.prov.cng.get_property = (hash_win32_cng_get_property_fn)GetProcAddress(hash_prov.prov.cng.dll, "BCryptGetProperty")) == NULL || (hash_prov.prov.cng.create_hash = (hash_win32_cng_create_hash_fn)GetProcAddress(hash_prov.prov.cng.dll, "BCryptCreateHash")) == NULL || (hash_prov.prov.cng.finish_hash = (hash_win32_cng_finish_hash_fn)GetProcAddress(hash_prov.prov.cng.dll, "BCryptFinishHash")) == NULL || (hash_prov.prov.cng.hash_data = (hash_win32_cng_hash_data_fn)GetProcAddress(hash_prov.prov.cng.dll, "BCryptHashData")) == NULL || (hash_prov.prov.cng.destroy_hash = (hash_win32_cng_destroy_hash_fn)GetProcAddress(hash_prov.prov.cng.dll, "BCryptDestroyHash")) == NULL || (hash_prov.prov.cng.close_algorithm_provider = (hash_win32_cng_close_algorithm_provider_fn)GetProcAddress(hash_prov.prov.cng.dll, "BCryptCloseAlgorithmProvider")) == NULL) { FreeLibrary(hash_prov.prov.cng.dll); git_error_set(GIT_ERROR_OS, "CryptoNG functions could not be loaded"); return -1; } /* Load the SHA1 algorithm */ if (hash_prov.prov.cng.open_algorithm_provider(&hash_prov.prov.cng.handle, GIT_HASH_CNG_HASH_TYPE, NULL, GIT_HASH_CNG_HASH_REUSABLE) < 0) { FreeLibrary(hash_prov.prov.cng.dll); git_error_set(GIT_ERROR_OS, "algorithm provider could not be initialized"); return -1; } /* Get storage space for the hash object */ if (hash_prov.prov.cng.get_property(hash_prov.prov.cng.handle, GIT_HASH_CNG_HASH_OBJECT_LEN, (PBYTE)&hash_prov.prov.cng.hash_object_size, sizeof(DWORD), &size_len, 0) < 0) { hash_prov.prov.cng.close_algorithm_provider(hash_prov.prov.cng.handle, 0); FreeLibrary(hash_prov.prov.cng.dll); git_error_set(GIT_ERROR_OS, "algorithm handle could not be found"); return -1; } hash_prov.type = CNG; return 0; } GIT_INLINE(void) hash_cng_prov_shutdown(void) { hash_prov.prov.cng.close_algorithm_provider(hash_prov.prov.cng.handle, 0); FreeLibrary(hash_prov.prov.cng.dll); hash_prov.type = INVALID; } /* Initialize CryptoAPI */ GIT_INLINE(int) hash_cryptoapi_prov_init() { if (!CryptAcquireContext(&hash_prov.prov.cryptoapi.handle, NULL, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { git_error_set(GIT_ERROR_OS, "legacy hash context could not be started"); return -1; } hash_prov.type = CRYPTOAPI; return 0; } GIT_INLINE(void) hash_cryptoapi_prov_shutdown(void) { CryptReleaseContext(hash_prov.prov.cryptoapi.handle, 0); hash_prov.type = INVALID; } static void sha1_shutdown(void) { if (hash_prov.type == CNG) hash_cng_prov_shutdown(); else if(hash_prov.type == CRYPTOAPI) hash_cryptoapi_prov_shutdown(); } int git_hash_sha1_global_init(void) { int error = 0; if (hash_prov.type != INVALID) return 0; if ((error = hash_cng_prov_init()) < 0) error = hash_cryptoapi_prov_init(); if (!error) error = git_runtime_shutdown_register(sha1_shutdown); return error; } /* CryptoAPI: available in Windows XP and newer */ GIT_INLINE(int) hash_ctx_cryptoapi_init(git_hash_sha1_ctx *ctx) { ctx->type = CRYPTOAPI; ctx->prov = &hash_prov; return git_hash_sha1_init(ctx); } GIT_INLINE(int) hash_cryptoapi_init(git_hash_sha1_ctx *ctx) { if (ctx->ctx.cryptoapi.valid) CryptDestroyHash(ctx->ctx.cryptoapi.hash_handle); if (!CryptCreateHash(ctx->prov->prov.cryptoapi.handle, CALG_SHA1, 0, 0, &ctx->ctx.cryptoapi.hash_handle)) { ctx->ctx.cryptoapi.valid = 0; git_error_set(GIT_ERROR_OS, "legacy hash implementation could not be created"); return -1; } ctx->ctx.cryptoapi.valid = 1; return 0; } GIT_INLINE(int) hash_cryptoapi_update(git_hash_sha1_ctx *ctx, const void *_data, size_t len) { const BYTE *data = (BYTE *)_data; GIT_ASSERT(ctx->ctx.cryptoapi.valid); while (len > 0) { DWORD chunk = (len > MAXDWORD) ? MAXDWORD : (DWORD)len; if (!CryptHashData(ctx->ctx.cryptoapi.hash_handle, data, chunk, 0)) { git_error_set(GIT_ERROR_OS, "legacy hash data could not be updated"); return -1; } data += chunk; len -= chunk; } return 0; } GIT_INLINE(int) hash_cryptoapi_final(git_oid *out, git_hash_sha1_ctx *ctx) { DWORD len = 20; int error = 0; GIT_ASSERT(ctx->ctx.cryptoapi.valid); if (!CryptGetHashParam(ctx->ctx.cryptoapi.hash_handle, HP_HASHVAL, out->id, &len, 0)) { git_error_set(GIT_ERROR_OS, "legacy hash data could not be finished"); error = -1; } CryptDestroyHash(ctx->ctx.cryptoapi.hash_handle); ctx->ctx.cryptoapi.valid = 0; return error; } GIT_INLINE(void) hash_ctx_cryptoapi_cleanup(git_hash_sha1_ctx *ctx) { if (ctx->ctx.cryptoapi.valid) CryptDestroyHash(ctx->ctx.cryptoapi.hash_handle); } /* CNG: Available in Windows Server 2008 and newer */ GIT_INLINE(int) hash_ctx_cng_init(git_hash_sha1_ctx *ctx) { if ((ctx->ctx.cng.hash_object = git__malloc(hash_prov.prov.cng.hash_object_size)) == NULL) return -1; if (hash_prov.prov.cng.create_hash(hash_prov.prov.cng.handle, &ctx->ctx.cng.hash_handle, ctx->ctx.cng.hash_object, hash_prov.prov.cng.hash_object_size, NULL, 0, 0) < 0) { git__free(ctx->ctx.cng.hash_object); git_error_set(GIT_ERROR_OS, "hash implementation could not be created"); return -1; } ctx->type = CNG; ctx->prov = &hash_prov; return 0; } GIT_INLINE(int) hash_cng_init(git_hash_sha1_ctx *ctx) { BYTE hash[GIT_OID_RAWSZ]; if (!ctx->ctx.cng.updated) return 0; /* CNG needs to be finished to restart */ if (ctx->prov->prov.cng.finish_hash(ctx->ctx.cng.hash_handle, hash, GIT_OID_RAWSZ, 0) < 0) { git_error_set(GIT_ERROR_OS, "hash implementation could not be finished"); return -1; } ctx->ctx.cng.updated = 0; return 0; } GIT_INLINE(int) hash_cng_update(git_hash_sha1_ctx *ctx, const void *_data, size_t len) { PBYTE data = (PBYTE)_data; while (len > 0) { ULONG chunk = (len > ULONG_MAX) ? ULONG_MAX : (ULONG)len; if (ctx->prov->prov.cng.hash_data(ctx->ctx.cng.hash_handle, data, chunk, 0) < 0) { git_error_set(GIT_ERROR_OS, "hash could not be updated"); return -1; } data += chunk; len -= chunk; } return 0; } GIT_INLINE(int) hash_cng_final(git_oid *out, git_hash_sha1_ctx *ctx) { if (ctx->prov->prov.cng.finish_hash(ctx->ctx.cng.hash_handle, out->id, GIT_OID_RAWSZ, 0) < 0) { git_error_set(GIT_ERROR_OS, "hash could not be finished"); return -1; } ctx->ctx.cng.updated = 0; return 0; } GIT_INLINE(void) hash_ctx_cng_cleanup(git_hash_sha1_ctx *ctx) { ctx->prov->prov.cng.destroy_hash(ctx->ctx.cng.hash_handle); git__free(ctx->ctx.cng.hash_object); } /* Indirection between CryptoAPI and CNG */ int git_hash_sha1_ctx_init(git_hash_sha1_ctx *ctx) { int error = 0; GIT_ASSERT_ARG(ctx); /* * When compiled with GIT_THREADS, the global hash_prov data is * initialized with git_libgit2_init. Otherwise, it must be initialized * at first use. */ if (hash_prov.type == INVALID && (error = git_hash_sha1_global_init()) < 0) return error; memset(ctx, 0x0, sizeof(git_hash_sha1_ctx)); return (hash_prov.type == CNG) ? hash_ctx_cng_init(ctx) : hash_ctx_cryptoapi_init(ctx); } int git_hash_sha1_init(git_hash_sha1_ctx *ctx) { GIT_ASSERT_ARG(ctx); GIT_ASSERT_ARG(ctx->type); return (ctx->type == CNG) ? hash_cng_init(ctx) : hash_cryptoapi_init(ctx); } int git_hash_sha1_update(git_hash_sha1_ctx *ctx, const void *data, size_t len) { GIT_ASSERT_ARG(ctx); GIT_ASSERT_ARG(ctx->type); return (ctx->type == CNG) ? hash_cng_update(ctx, data, len) : hash_cryptoapi_update(ctx, data, len); } int git_hash_sha1_final(git_oid *out, git_hash_sha1_ctx *ctx) { GIT_ASSERT_ARG(ctx); GIT_ASSERT_ARG(ctx->type); return (ctx->type == CNG) ? hash_cng_final(out, ctx) : hash_cryptoapi_final(out, ctx); } void git_hash_sha1_ctx_cleanup(git_hash_sha1_ctx *ctx) { if (!ctx) return; else if (ctx->type == CNG) hash_ctx_cng_cleanup(ctx); else if(ctx->type == CRYPTOAPI) hash_ctx_cryptoapi_cleanup(ctx); }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash/sha1/mbedtls.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "mbedtls.h" int git_hash_sha1_global_init(void) { return 0; } int git_hash_sha1_ctx_init(git_hash_sha1_ctx *ctx) { return git_hash_sha1_init(ctx); } void git_hash_sha1_ctx_cleanup(git_hash_sha1_ctx *ctx) { if (ctx) mbedtls_sha1_free(&ctx->c); } int git_hash_sha1_init(git_hash_sha1_ctx *ctx) { GIT_ASSERT_ARG(ctx); mbedtls_sha1_init(&ctx->c); mbedtls_sha1_starts(&ctx->c); return 0; } int git_hash_sha1_update(git_hash_sha1_ctx *ctx, const void *data, size_t len) { GIT_ASSERT_ARG(ctx); mbedtls_sha1_update(&ctx->c, data, len); return 0; } int git_hash_sha1_final(git_oid *out, git_hash_sha1_ctx *ctx) { GIT_ASSERT_ARG(ctx); mbedtls_sha1_finish(&ctx->c, out->id); return 0; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash/sha1/common_crypto.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "common_crypto.h" #define CC_LONG_MAX ((CC_LONG)-1) int git_hash_sha1_global_init(void) { return 0; } int git_hash_sha1_ctx_init(git_hash_sha1_ctx *ctx) { return git_hash_sha1_init(ctx); } void git_hash_sha1_ctx_cleanup(git_hash_sha1_ctx *ctx) { GIT_UNUSED(ctx); } int git_hash_sha1_init(git_hash_sha1_ctx *ctx) { GIT_ASSERT_ARG(ctx); CC_SHA1_Init(&ctx->c); return 0; } int git_hash_sha1_update(git_hash_sha1_ctx *ctx, const void *_data, size_t len) { const unsigned char *data = _data; GIT_ASSERT_ARG(ctx); while (len > 0) { CC_LONG chunk = (len > CC_LONG_MAX) ? CC_LONG_MAX : (CC_LONG)len; CC_SHA1_Update(&ctx->c, data, chunk); data += chunk; len -= chunk; } return 0; } int git_hash_sha1_final(git_oid *out, git_hash_sha1_ctx *ctx) { GIT_ASSERT_ARG(ctx); CC_SHA1_Final(out->id, &ctx->c); return 0; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash/sha1/mbedtls.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_hash_sha1_mbedtls_h__ #define INCLUDE_hash_sha1_mbedtls_h__ #include "hash/sha1.h" #include <mbedtls/sha1.h> struct git_hash_sha1_ctx { mbedtls_sha1_context c; }; #endif /* INCLUDE_hash_sha1_mbedtls_h__ */
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash/sha1
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash/sha1/sha1dc/ubc_check.h
/*** * Copyright 2017 Marc Stevens <[email protected]>, Dan Shumow <[email protected]> * Distributed under the MIT Software License. * See accompanying file LICENSE.txt or copy at * https://opensource.org/licenses/MIT ***/ /* // this file was generated by the 'parse_bitrel' program in the tools section // using the data files from directory 'tools/data/3565' // // sha1_dvs contains a list of SHA-1 Disturbance Vectors (DV) to check // dvType, dvK and dvB define the DV: I(K,B) or II(K,B) (see the paper) // dm[80] is the expanded message block XOR-difference defined by the DV // testt is the step to do the recompression from for collision detection // maski and maskb define the bit to check for each DV in the dvmask returned by ubc_check // // ubc_check takes as input an expanded message block and verifies the unavoidable bitconditions for all listed DVs // it returns a dvmask where each bit belonging to a DV is set if all unavoidable bitconditions for that DV have been met // thus one needs to do the recompression check for each DV that has its bit set */ #ifndef SHA1DC_UBC_CHECK_H #define SHA1DC_UBC_CHECK_H #if defined(__cplusplus) extern "C" { #endif #ifndef SHA1DC_NO_STANDARD_INCLUDES #include <stdint.h> #endif #define DVMASKSIZE 1 typedef struct { int dvType; int dvK; int dvB; int testt; int maski; int maskb; uint32_t dm[80]; } dv_info_t; extern dv_info_t sha1_dvs[]; void ubc_check(const uint32_t W[80], uint32_t dvmask[DVMASKSIZE]); #define DOSTORESTATE58 #define DOSTORESTATE65 #define CHECK_DVMASK(_DVMASK) (0 != _DVMASK[0]) #if defined(__cplusplus) } #endif #ifdef SHA1DC_CUSTOM_TRAILING_INCLUDE_UBC_CHECK_H #include SHA1DC_CUSTOM_TRAILING_INCLUDE_UBC_CHECK_H #endif #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash/sha1
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash/sha1/sha1dc/sha1.c
/*** * Copyright 2017 Marc Stevens <[email protected]>, Dan Shumow ([email protected]) * Distributed under the MIT Software License. * See accompanying file LICENSE.txt or copy at * https://opensource.org/licenses/MIT ***/ #ifndef SHA1DC_NO_STANDARD_INCLUDES #include <string.h> #include <memory.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> /* make sure macros like _BIG_ENDIAN visible */ #endif #ifdef SHA1DC_CUSTOM_INCLUDE_SHA1_C #include SHA1DC_CUSTOM_INCLUDE_SHA1_C #endif #ifndef SHA1DC_INIT_SAFE_HASH_DEFAULT #define SHA1DC_INIT_SAFE_HASH_DEFAULT 1 #endif #include "sha1.h" #include "ubc_check.h" #if (defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) || \ defined(i386) || defined(__i386) || defined(__i386__) || defined(__i486__) || \ defined(__i586__) || defined(__i686__) || defined(_M_IX86) || defined(__X86__) || \ defined(_X86_) || defined(__THW_INTEL__) || defined(__I86__) || defined(__INTEL__) || \ defined(__386) || defined(_M_X64) || defined(_M_AMD64)) #define SHA1DC_ON_INTEL_LIKE_PROCESSOR #endif /* Because Little-Endian architectures are most common, we only set SHA1DC_BIGENDIAN if one of these conditions is met. Note that all MSFT platforms are little endian, so none of these will be defined under the MSC compiler. If you are compiling on a big endian platform and your compiler does not define one of these, you will have to add whatever macros your tool chain defines to indicate Big-Endianness. */ #if defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) /* * Should detect Big Endian under GCC since at least 4.6.0 (gcc svn * rev #165881). See * https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html * * This also works under clang since 3.2, it copied the GCC-ism. See * clang.git's 3b198a97d2 ("Preprocessor: add __BYTE_ORDER__ * predefined macro", 2012-07-27) */ #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ #define SHA1DC_BIGENDIAN #endif /* Not under GCC-alike */ #elif defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) /* * Should detect Big Endian under glibc.git since 14245eb70e ("entered * into RCS", 1992-11-25). Defined in <endian.h> which will have been * brought in by standard headers. See glibc.git and * https://sourceforge.net/p/predef/wiki/Endianness/ */ #if __BYTE_ORDER == __BIG_ENDIAN #define SHA1DC_BIGENDIAN #endif /* Not under GCC-alike or glibc */ #elif defined(_BYTE_ORDER) && defined(_BIG_ENDIAN) && defined(_LITTLE_ENDIAN) /* * *BSD and newlib (embeded linux, cygwin, etc). * the defined(_BIG_ENDIAN) && defined(_LITTLE_ENDIAN) part prevents * this condition from matching with Solaris/sparc. * (Solaris defines only one endian macro) */ #if _BYTE_ORDER == _BIG_ENDIAN #define SHA1DC_BIGENDIAN #endif /* Not under GCC-alike or glibc or *BSD or newlib */ #elif (defined(__ARMEB__) || defined(__THUMBEB__) || defined(__AARCH64EB__) || \ defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || \ defined(__sparc)) /* * Should define Big Endian for a whitelist of known processors. See * https://sourceforge.net/p/predef/wiki/Endianness/ and * http://www.oracle.com/technetwork/server-storage/solaris/portingtosolaris-138514.html */ #define SHA1DC_BIGENDIAN /* Not under GCC-alike or glibc or *BSD or newlib or <processor whitelist> */ #elif (defined(_AIX) || defined(__hpux)) /* * Defines Big Endian on a whitelist of OSs that are known to be Big * Endian-only. See * https://public-inbox.org/git/[email protected]/ */ #define SHA1DC_BIGENDIAN /* Not under GCC-alike or glibc or *BSD or newlib or <processor whitelist> or <os whitelist> */ #elif defined(SHA1DC_ON_INTEL_LIKE_PROCESSOR) /* * As a last resort before we do anything else we're not 100% sure * about below, we blacklist specific processors here. We could add * more, see e.g. https://wiki.debian.org/ArchitectureSpecificsMemo */ #else /* Not under GCC-alike or glibc or *BSD or newlib or <processor whitelist> or <os whitelist> or <processor blacklist> */ /* We do nothing more here for now */ /*#error "Uncomment this to see if you fall through all the detection"*/ #endif /* Big Endian detection */ #if (defined(SHA1DC_FORCE_LITTLEENDIAN) && defined(SHA1DC_BIGENDIAN)) #undef SHA1DC_BIGENDIAN #endif #if (defined(SHA1DC_FORCE_BIGENDIAN) && !defined(SHA1DC_BIGENDIAN)) #define SHA1DC_BIGENDIAN #endif /*ENDIANNESS SELECTION*/ #ifndef SHA1DC_FORCE_ALIGNED_ACCESS #if defined(SHA1DC_FORCE_UNALIGNED_ACCESS) || defined(SHA1DC_ON_INTEL_LIKE_PROCESSOR) #define SHA1DC_ALLOW_UNALIGNED_ACCESS #endif /*UNALIGNED ACCESS DETECTION*/ #endif /*FORCE ALIGNED ACCESS*/ #define rotate_right(x,n) (((x)>>(n))|((x)<<(32-(n)))) #define rotate_left(x,n) (((x)<<(n))|((x)>>(32-(n)))) #define sha1_bswap32(x) \ {x = ((x << 8) & 0xFF00FF00) | ((x >> 8) & 0xFF00FF); x = (x << 16) | (x >> 16);} #define sha1_mix(W, t) (rotate_left(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1)) #ifdef SHA1DC_BIGENDIAN #define sha1_load(m, t, temp) { temp = m[t]; } #else #define sha1_load(m, t, temp) { temp = m[t]; sha1_bswap32(temp); } #endif #define sha1_store(W, t, x) *(volatile uint32_t *)&W[t] = x #define sha1_f1(b,c,d) ((d)^((b)&((c)^(d)))) #define sha1_f2(b,c,d) ((b)^(c)^(d)) #define sha1_f3(b,c,d) (((b)&(c))+((d)&((b)^(c)))) #define sha1_f4(b,c,d) ((b)^(c)^(d)) #define HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, m, t) \ { e += rotate_left(a, 5) + sha1_f1(b,c,d) + 0x5A827999 + m[t]; b = rotate_left(b, 30); } #define HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, m, t) \ { e += rotate_left(a, 5) + sha1_f2(b,c,d) + 0x6ED9EBA1 + m[t]; b = rotate_left(b, 30); } #define HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, m, t) \ { e += rotate_left(a, 5) + sha1_f3(b,c,d) + 0x8F1BBCDC + m[t]; b = rotate_left(b, 30); } #define HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, m, t) \ { e += rotate_left(a, 5) + sha1_f4(b,c,d) + 0xCA62C1D6 + m[t]; b = rotate_left(b, 30); } #define HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(a, b, c, d, e, m, t) \ { b = rotate_right(b, 30); e -= rotate_left(a, 5) + sha1_f1(b,c,d) + 0x5A827999 + m[t]; } #define HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(a, b, c, d, e, m, t) \ { b = rotate_right(b, 30); e -= rotate_left(a, 5) + sha1_f2(b,c,d) + 0x6ED9EBA1 + m[t]; } #define HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(a, b, c, d, e, m, t) \ { b = rotate_right(b, 30); e -= rotate_left(a, 5) + sha1_f3(b,c,d) + 0x8F1BBCDC + m[t]; } #define HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(a, b, c, d, e, m, t) \ { b = rotate_right(b, 30); e -= rotate_left(a, 5) + sha1_f4(b,c,d) + 0xCA62C1D6 + m[t]; } #define SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(a, b, c, d, e, m, W, t, temp) \ {sha1_load(m, t, temp); sha1_store(W, t, temp); e += temp + rotate_left(a, 5) + sha1_f1(b,c,d) + 0x5A827999; b = rotate_left(b, 30);} #define SHA1COMPRESS_FULL_ROUND1_STEP_EXPAND(a, b, c, d, e, W, t, temp) \ {temp = sha1_mix(W, t); sha1_store(W, t, temp); e += temp + rotate_left(a, 5) + sha1_f1(b,c,d) + 0x5A827999; b = rotate_left(b, 30); } #define SHA1COMPRESS_FULL_ROUND2_STEP(a, b, c, d, e, W, t, temp) \ {temp = sha1_mix(W, t); sha1_store(W, t, temp); e += temp + rotate_left(a, 5) + sha1_f2(b,c,d) + 0x6ED9EBA1; b = rotate_left(b, 30); } #define SHA1COMPRESS_FULL_ROUND3_STEP(a, b, c, d, e, W, t, temp) \ {temp = sha1_mix(W, t); sha1_store(W, t, temp); e += temp + rotate_left(a, 5) + sha1_f3(b,c,d) + 0x8F1BBCDC; b = rotate_left(b, 30); } #define SHA1COMPRESS_FULL_ROUND4_STEP(a, b, c, d, e, W, t, temp) \ {temp = sha1_mix(W, t); sha1_store(W, t, temp); e += temp + rotate_left(a, 5) + sha1_f4(b,c,d) + 0xCA62C1D6; b = rotate_left(b, 30); } #define SHA1_STORE_STATE(i) states[i][0] = a; states[i][1] = b; states[i][2] = c; states[i][3] = d; states[i][4] = e; #ifdef BUILDNOCOLLDETECTSHA1COMPRESSION void sha1_compression(uint32_t ihv[5], const uint32_t m[16]) { uint32_t W[80]; uint32_t a,b,c,d,e; unsigned i; memcpy(W, m, 16 * 4); for (i = 16; i < 80; ++i) W[i] = sha1_mix(W, i); a = ihv[0]; b = ihv[1]; c = ihv[2]; d = ihv[3]; e = ihv[4]; HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, W, 0); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, W, 1); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, W, 2); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, W, 3); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, W, 4); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, W, 5); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, W, 6); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, W, 7); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, W, 8); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, W, 9); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, W, 10); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, W, 11); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, W, 12); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, W, 13); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, W, 14); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, W, 15); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, W, 16); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, W, 17); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, W, 18); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, W, 19); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, W, 20); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, W, 21); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, W, 22); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, W, 23); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, W, 24); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, W, 25); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, W, 26); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, W, 27); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, W, 28); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, W, 29); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, W, 30); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, W, 31); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, W, 32); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, W, 33); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, W, 34); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, W, 35); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, W, 36); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, W, 37); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, W, 38); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, W, 39); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, W, 40); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, W, 41); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, W, 42); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, W, 43); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, W, 44); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, W, 45); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, W, 46); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, W, 47); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, W, 48); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, W, 49); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, W, 50); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, W, 51); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, W, 52); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, W, 53); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, W, 54); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, W, 55); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, W, 56); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, W, 57); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, W, 58); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, W, 59); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, W, 60); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, W, 61); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, W, 62); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, W, 63); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, W, 64); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, W, 65); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, W, 66); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, W, 67); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, W, 68); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, W, 69); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, W, 70); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, W, 71); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, W, 72); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, W, 73); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, W, 74); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, W, 75); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, W, 76); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, W, 77); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, W, 78); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, W, 79); ihv[0] += a; ihv[1] += b; ihv[2] += c; ihv[3] += d; ihv[4] += e; } #endif /*BUILDNOCOLLDETECTSHA1COMPRESSION*/ static void sha1_compression_W(uint32_t ihv[5], const uint32_t W[80]) { uint32_t a = ihv[0], b = ihv[1], c = ihv[2], d = ihv[3], e = ihv[4]; HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, W, 0); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, W, 1); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, W, 2); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, W, 3); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, W, 4); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, W, 5); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, W, 6); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, W, 7); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, W, 8); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, W, 9); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, W, 10); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, W, 11); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, W, 12); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, W, 13); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, W, 14); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, W, 15); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, W, 16); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, W, 17); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, W, 18); HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, W, 19); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, W, 20); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, W, 21); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, W, 22); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, W, 23); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, W, 24); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, W, 25); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, W, 26); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, W, 27); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, W, 28); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, W, 29); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, W, 30); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, W, 31); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, W, 32); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, W, 33); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, W, 34); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, W, 35); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, W, 36); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, W, 37); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, W, 38); HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, W, 39); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, W, 40); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, W, 41); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, W, 42); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, W, 43); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, W, 44); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, W, 45); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, W, 46); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, W, 47); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, W, 48); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, W, 49); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, W, 50); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, W, 51); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, W, 52); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, W, 53); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, W, 54); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, W, 55); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, W, 56); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, W, 57); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, W, 58); HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, W, 59); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, W, 60); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, W, 61); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, W, 62); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, W, 63); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, W, 64); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, W, 65); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, W, 66); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, W, 67); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, W, 68); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, W, 69); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, W, 70); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, W, 71); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, W, 72); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, W, 73); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, W, 74); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, W, 75); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, W, 76); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, W, 77); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, W, 78); HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, W, 79); ihv[0] += a; ihv[1] += b; ihv[2] += c; ihv[3] += d; ihv[4] += e; } void sha1_compression_states(uint32_t ihv[5], const uint32_t m[16], uint32_t W[80], uint32_t states[80][5]) { uint32_t a = ihv[0], b = ihv[1], c = ihv[2], d = ihv[3], e = ihv[4]; uint32_t temp; #ifdef DOSTORESTATE00 SHA1_STORE_STATE(0) #endif SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(a, b, c, d, e, m, W, 0, temp); #ifdef DOSTORESTATE01 SHA1_STORE_STATE(1) #endif SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(e, a, b, c, d, m, W, 1, temp); #ifdef DOSTORESTATE02 SHA1_STORE_STATE(2) #endif SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(d, e, a, b, c, m, W, 2, temp); #ifdef DOSTORESTATE03 SHA1_STORE_STATE(3) #endif SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(c, d, e, a, b, m, W, 3, temp); #ifdef DOSTORESTATE04 SHA1_STORE_STATE(4) #endif SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(b, c, d, e, a, m, W, 4, temp); #ifdef DOSTORESTATE05 SHA1_STORE_STATE(5) #endif SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(a, b, c, d, e, m, W, 5, temp); #ifdef DOSTORESTATE06 SHA1_STORE_STATE(6) #endif SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(e, a, b, c, d, m, W, 6, temp); #ifdef DOSTORESTATE07 SHA1_STORE_STATE(7) #endif SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(d, e, a, b, c, m, W, 7, temp); #ifdef DOSTORESTATE08 SHA1_STORE_STATE(8) #endif SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(c, d, e, a, b, m, W, 8, temp); #ifdef DOSTORESTATE09 SHA1_STORE_STATE(9) #endif SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(b, c, d, e, a, m, W, 9, temp); #ifdef DOSTORESTATE10 SHA1_STORE_STATE(10) #endif SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(a, b, c, d, e, m, W, 10, temp); #ifdef DOSTORESTATE11 SHA1_STORE_STATE(11) #endif SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(e, a, b, c, d, m, W, 11, temp); #ifdef DOSTORESTATE12 SHA1_STORE_STATE(12) #endif SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(d, e, a, b, c, m, W, 12, temp); #ifdef DOSTORESTATE13 SHA1_STORE_STATE(13) #endif SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(c, d, e, a, b, m, W, 13, temp); #ifdef DOSTORESTATE14 SHA1_STORE_STATE(14) #endif SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(b, c, d, e, a, m, W, 14, temp); #ifdef DOSTORESTATE15 SHA1_STORE_STATE(15) #endif SHA1COMPRESS_FULL_ROUND1_STEP_LOAD(a, b, c, d, e, m, W, 15, temp); #ifdef DOSTORESTATE16 SHA1_STORE_STATE(16) #endif SHA1COMPRESS_FULL_ROUND1_STEP_EXPAND(e, a, b, c, d, W, 16, temp); #ifdef DOSTORESTATE17 SHA1_STORE_STATE(17) #endif SHA1COMPRESS_FULL_ROUND1_STEP_EXPAND(d, e, a, b, c, W, 17, temp); #ifdef DOSTORESTATE18 SHA1_STORE_STATE(18) #endif SHA1COMPRESS_FULL_ROUND1_STEP_EXPAND(c, d, e, a, b, W, 18, temp); #ifdef DOSTORESTATE19 SHA1_STORE_STATE(19) #endif SHA1COMPRESS_FULL_ROUND1_STEP_EXPAND(b, c, d, e, a, W, 19, temp); #ifdef DOSTORESTATE20 SHA1_STORE_STATE(20) #endif SHA1COMPRESS_FULL_ROUND2_STEP(a, b, c, d, e, W, 20, temp); #ifdef DOSTORESTATE21 SHA1_STORE_STATE(21) #endif SHA1COMPRESS_FULL_ROUND2_STEP(e, a, b, c, d, W, 21, temp); #ifdef DOSTORESTATE22 SHA1_STORE_STATE(22) #endif SHA1COMPRESS_FULL_ROUND2_STEP(d, e, a, b, c, W, 22, temp); #ifdef DOSTORESTATE23 SHA1_STORE_STATE(23) #endif SHA1COMPRESS_FULL_ROUND2_STEP(c, d, e, a, b, W, 23, temp); #ifdef DOSTORESTATE24 SHA1_STORE_STATE(24) #endif SHA1COMPRESS_FULL_ROUND2_STEP(b, c, d, e, a, W, 24, temp); #ifdef DOSTORESTATE25 SHA1_STORE_STATE(25) #endif SHA1COMPRESS_FULL_ROUND2_STEP(a, b, c, d, e, W, 25, temp); #ifdef DOSTORESTATE26 SHA1_STORE_STATE(26) #endif SHA1COMPRESS_FULL_ROUND2_STEP(e, a, b, c, d, W, 26, temp); #ifdef DOSTORESTATE27 SHA1_STORE_STATE(27) #endif SHA1COMPRESS_FULL_ROUND2_STEP(d, e, a, b, c, W, 27, temp); #ifdef DOSTORESTATE28 SHA1_STORE_STATE(28) #endif SHA1COMPRESS_FULL_ROUND2_STEP(c, d, e, a, b, W, 28, temp); #ifdef DOSTORESTATE29 SHA1_STORE_STATE(29) #endif SHA1COMPRESS_FULL_ROUND2_STEP(b, c, d, e, a, W, 29, temp); #ifdef DOSTORESTATE30 SHA1_STORE_STATE(30) #endif SHA1COMPRESS_FULL_ROUND2_STEP(a, b, c, d, e, W, 30, temp); #ifdef DOSTORESTATE31 SHA1_STORE_STATE(31) #endif SHA1COMPRESS_FULL_ROUND2_STEP(e, a, b, c, d, W, 31, temp); #ifdef DOSTORESTATE32 SHA1_STORE_STATE(32) #endif SHA1COMPRESS_FULL_ROUND2_STEP(d, e, a, b, c, W, 32, temp); #ifdef DOSTORESTATE33 SHA1_STORE_STATE(33) #endif SHA1COMPRESS_FULL_ROUND2_STEP(c, d, e, a, b, W, 33, temp); #ifdef DOSTORESTATE34 SHA1_STORE_STATE(34) #endif SHA1COMPRESS_FULL_ROUND2_STEP(b, c, d, e, a, W, 34, temp); #ifdef DOSTORESTATE35 SHA1_STORE_STATE(35) #endif SHA1COMPRESS_FULL_ROUND2_STEP(a, b, c, d, e, W, 35, temp); #ifdef DOSTORESTATE36 SHA1_STORE_STATE(36) #endif SHA1COMPRESS_FULL_ROUND2_STEP(e, a, b, c, d, W, 36, temp); #ifdef DOSTORESTATE37 SHA1_STORE_STATE(37) #endif SHA1COMPRESS_FULL_ROUND2_STEP(d, e, a, b, c, W, 37, temp); #ifdef DOSTORESTATE38 SHA1_STORE_STATE(38) #endif SHA1COMPRESS_FULL_ROUND2_STEP(c, d, e, a, b, W, 38, temp); #ifdef DOSTORESTATE39 SHA1_STORE_STATE(39) #endif SHA1COMPRESS_FULL_ROUND2_STEP(b, c, d, e, a, W, 39, temp); #ifdef DOSTORESTATE40 SHA1_STORE_STATE(40) #endif SHA1COMPRESS_FULL_ROUND3_STEP(a, b, c, d, e, W, 40, temp); #ifdef DOSTORESTATE41 SHA1_STORE_STATE(41) #endif SHA1COMPRESS_FULL_ROUND3_STEP(e, a, b, c, d, W, 41, temp); #ifdef DOSTORESTATE42 SHA1_STORE_STATE(42) #endif SHA1COMPRESS_FULL_ROUND3_STEP(d, e, a, b, c, W, 42, temp); #ifdef DOSTORESTATE43 SHA1_STORE_STATE(43) #endif SHA1COMPRESS_FULL_ROUND3_STEP(c, d, e, a, b, W, 43, temp); #ifdef DOSTORESTATE44 SHA1_STORE_STATE(44) #endif SHA1COMPRESS_FULL_ROUND3_STEP(b, c, d, e, a, W, 44, temp); #ifdef DOSTORESTATE45 SHA1_STORE_STATE(45) #endif SHA1COMPRESS_FULL_ROUND3_STEP(a, b, c, d, e, W, 45, temp); #ifdef DOSTORESTATE46 SHA1_STORE_STATE(46) #endif SHA1COMPRESS_FULL_ROUND3_STEP(e, a, b, c, d, W, 46, temp); #ifdef DOSTORESTATE47 SHA1_STORE_STATE(47) #endif SHA1COMPRESS_FULL_ROUND3_STEP(d, e, a, b, c, W, 47, temp); #ifdef DOSTORESTATE48 SHA1_STORE_STATE(48) #endif SHA1COMPRESS_FULL_ROUND3_STEP(c, d, e, a, b, W, 48, temp); #ifdef DOSTORESTATE49 SHA1_STORE_STATE(49) #endif SHA1COMPRESS_FULL_ROUND3_STEP(b, c, d, e, a, W, 49, temp); #ifdef DOSTORESTATE50 SHA1_STORE_STATE(50) #endif SHA1COMPRESS_FULL_ROUND3_STEP(a, b, c, d, e, W, 50, temp); #ifdef DOSTORESTATE51 SHA1_STORE_STATE(51) #endif SHA1COMPRESS_FULL_ROUND3_STEP(e, a, b, c, d, W, 51, temp); #ifdef DOSTORESTATE52 SHA1_STORE_STATE(52) #endif SHA1COMPRESS_FULL_ROUND3_STEP(d, e, a, b, c, W, 52, temp); #ifdef DOSTORESTATE53 SHA1_STORE_STATE(53) #endif SHA1COMPRESS_FULL_ROUND3_STEP(c, d, e, a, b, W, 53, temp); #ifdef DOSTORESTATE54 SHA1_STORE_STATE(54) #endif SHA1COMPRESS_FULL_ROUND3_STEP(b, c, d, e, a, W, 54, temp); #ifdef DOSTORESTATE55 SHA1_STORE_STATE(55) #endif SHA1COMPRESS_FULL_ROUND3_STEP(a, b, c, d, e, W, 55, temp); #ifdef DOSTORESTATE56 SHA1_STORE_STATE(56) #endif SHA1COMPRESS_FULL_ROUND3_STEP(e, a, b, c, d, W, 56, temp); #ifdef DOSTORESTATE57 SHA1_STORE_STATE(57) #endif SHA1COMPRESS_FULL_ROUND3_STEP(d, e, a, b, c, W, 57, temp); #ifdef DOSTORESTATE58 SHA1_STORE_STATE(58) #endif SHA1COMPRESS_FULL_ROUND3_STEP(c, d, e, a, b, W, 58, temp); #ifdef DOSTORESTATE59 SHA1_STORE_STATE(59) #endif SHA1COMPRESS_FULL_ROUND3_STEP(b, c, d, e, a, W, 59, temp); #ifdef DOSTORESTATE60 SHA1_STORE_STATE(60) #endif SHA1COMPRESS_FULL_ROUND4_STEP(a, b, c, d, e, W, 60, temp); #ifdef DOSTORESTATE61 SHA1_STORE_STATE(61) #endif SHA1COMPRESS_FULL_ROUND4_STEP(e, a, b, c, d, W, 61, temp); #ifdef DOSTORESTATE62 SHA1_STORE_STATE(62) #endif SHA1COMPRESS_FULL_ROUND4_STEP(d, e, a, b, c, W, 62, temp); #ifdef DOSTORESTATE63 SHA1_STORE_STATE(63) #endif SHA1COMPRESS_FULL_ROUND4_STEP(c, d, e, a, b, W, 63, temp); #ifdef DOSTORESTATE64 SHA1_STORE_STATE(64) #endif SHA1COMPRESS_FULL_ROUND4_STEP(b, c, d, e, a, W, 64, temp); #ifdef DOSTORESTATE65 SHA1_STORE_STATE(65) #endif SHA1COMPRESS_FULL_ROUND4_STEP(a, b, c, d, e, W, 65, temp); #ifdef DOSTORESTATE66 SHA1_STORE_STATE(66) #endif SHA1COMPRESS_FULL_ROUND4_STEP(e, a, b, c, d, W, 66, temp); #ifdef DOSTORESTATE67 SHA1_STORE_STATE(67) #endif SHA1COMPRESS_FULL_ROUND4_STEP(d, e, a, b, c, W, 67, temp); #ifdef DOSTORESTATE68 SHA1_STORE_STATE(68) #endif SHA1COMPRESS_FULL_ROUND4_STEP(c, d, e, a, b, W, 68, temp); #ifdef DOSTORESTATE69 SHA1_STORE_STATE(69) #endif SHA1COMPRESS_FULL_ROUND4_STEP(b, c, d, e, a, W, 69, temp); #ifdef DOSTORESTATE70 SHA1_STORE_STATE(70) #endif SHA1COMPRESS_FULL_ROUND4_STEP(a, b, c, d, e, W, 70, temp); #ifdef DOSTORESTATE71 SHA1_STORE_STATE(71) #endif SHA1COMPRESS_FULL_ROUND4_STEP(e, a, b, c, d, W, 71, temp); #ifdef DOSTORESTATE72 SHA1_STORE_STATE(72) #endif SHA1COMPRESS_FULL_ROUND4_STEP(d, e, a, b, c, W, 72, temp); #ifdef DOSTORESTATE73 SHA1_STORE_STATE(73) #endif SHA1COMPRESS_FULL_ROUND4_STEP(c, d, e, a, b, W, 73, temp); #ifdef DOSTORESTATE74 SHA1_STORE_STATE(74) #endif SHA1COMPRESS_FULL_ROUND4_STEP(b, c, d, e, a, W, 74, temp); #ifdef DOSTORESTATE75 SHA1_STORE_STATE(75) #endif SHA1COMPRESS_FULL_ROUND4_STEP(a, b, c, d, e, W, 75, temp); #ifdef DOSTORESTATE76 SHA1_STORE_STATE(76) #endif SHA1COMPRESS_FULL_ROUND4_STEP(e, a, b, c, d, W, 76, temp); #ifdef DOSTORESTATE77 SHA1_STORE_STATE(77) #endif SHA1COMPRESS_FULL_ROUND4_STEP(d, e, a, b, c, W, 77, temp); #ifdef DOSTORESTATE78 SHA1_STORE_STATE(78) #endif SHA1COMPRESS_FULL_ROUND4_STEP(c, d, e, a, b, W, 78, temp); #ifdef DOSTORESTATE79 SHA1_STORE_STATE(79) #endif SHA1COMPRESS_FULL_ROUND4_STEP(b, c, d, e, a, W, 79, temp); ihv[0] += a; ihv[1] += b; ihv[2] += c; ihv[3] += d; ihv[4] += e; } #define SHA1_RECOMPRESS(t) \ static void sha1recompress_fast_ ## t (uint32_t ihvin[5], uint32_t ihvout[5], const uint32_t me2[80], const uint32_t state[5]) \ { \ uint32_t a = state[0], b = state[1], c = state[2], d = state[3], e = state[4]; \ if (t > 79) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(b, c, d, e, a, me2, 79); \ if (t > 78) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(c, d, e, a, b, me2, 78); \ if (t > 77) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(d, e, a, b, c, me2, 77); \ if (t > 76) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(e, a, b, c, d, me2, 76); \ if (t > 75) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(a, b, c, d, e, me2, 75); \ if (t > 74) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(b, c, d, e, a, me2, 74); \ if (t > 73) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(c, d, e, a, b, me2, 73); \ if (t > 72) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(d, e, a, b, c, me2, 72); \ if (t > 71) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(e, a, b, c, d, me2, 71); \ if (t > 70) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(a, b, c, d, e, me2, 70); \ if (t > 69) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(b, c, d, e, a, me2, 69); \ if (t > 68) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(c, d, e, a, b, me2, 68); \ if (t > 67) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(d, e, a, b, c, me2, 67); \ if (t > 66) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(e, a, b, c, d, me2, 66); \ if (t > 65) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(a, b, c, d, e, me2, 65); \ if (t > 64) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(b, c, d, e, a, me2, 64); \ if (t > 63) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(c, d, e, a, b, me2, 63); \ if (t > 62) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(d, e, a, b, c, me2, 62); \ if (t > 61) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(e, a, b, c, d, me2, 61); \ if (t > 60) HASHCLASH_SHA1COMPRESS_ROUND4_STEP_BW(a, b, c, d, e, me2, 60); \ if (t > 59) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(b, c, d, e, a, me2, 59); \ if (t > 58) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(c, d, e, a, b, me2, 58); \ if (t > 57) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(d, e, a, b, c, me2, 57); \ if (t > 56) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(e, a, b, c, d, me2, 56); \ if (t > 55) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(a, b, c, d, e, me2, 55); \ if (t > 54) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(b, c, d, e, a, me2, 54); \ if (t > 53) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(c, d, e, a, b, me2, 53); \ if (t > 52) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(d, e, a, b, c, me2, 52); \ if (t > 51) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(e, a, b, c, d, me2, 51); \ if (t > 50) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(a, b, c, d, e, me2, 50); \ if (t > 49) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(b, c, d, e, a, me2, 49); \ if (t > 48) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(c, d, e, a, b, me2, 48); \ if (t > 47) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(d, e, a, b, c, me2, 47); \ if (t > 46) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(e, a, b, c, d, me2, 46); \ if (t > 45) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(a, b, c, d, e, me2, 45); \ if (t > 44) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(b, c, d, e, a, me2, 44); \ if (t > 43) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(c, d, e, a, b, me2, 43); \ if (t > 42) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(d, e, a, b, c, me2, 42); \ if (t > 41) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(e, a, b, c, d, me2, 41); \ if (t > 40) HASHCLASH_SHA1COMPRESS_ROUND3_STEP_BW(a, b, c, d, e, me2, 40); \ if (t > 39) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(b, c, d, e, a, me2, 39); \ if (t > 38) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(c, d, e, a, b, me2, 38); \ if (t > 37) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(d, e, a, b, c, me2, 37); \ if (t > 36) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(e, a, b, c, d, me2, 36); \ if (t > 35) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(a, b, c, d, e, me2, 35); \ if (t > 34) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(b, c, d, e, a, me2, 34); \ if (t > 33) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(c, d, e, a, b, me2, 33); \ if (t > 32) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(d, e, a, b, c, me2, 32); \ if (t > 31) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(e, a, b, c, d, me2, 31); \ if (t > 30) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(a, b, c, d, e, me2, 30); \ if (t > 29) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(b, c, d, e, a, me2, 29); \ if (t > 28) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(c, d, e, a, b, me2, 28); \ if (t > 27) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(d, e, a, b, c, me2, 27); \ if (t > 26) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(e, a, b, c, d, me2, 26); \ if (t > 25) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(a, b, c, d, e, me2, 25); \ if (t > 24) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(b, c, d, e, a, me2, 24); \ if (t > 23) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(c, d, e, a, b, me2, 23); \ if (t > 22) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(d, e, a, b, c, me2, 22); \ if (t > 21) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(e, a, b, c, d, me2, 21); \ if (t > 20) HASHCLASH_SHA1COMPRESS_ROUND2_STEP_BW(a, b, c, d, e, me2, 20); \ if (t > 19) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(b, c, d, e, a, me2, 19); \ if (t > 18) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(c, d, e, a, b, me2, 18); \ if (t > 17) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(d, e, a, b, c, me2, 17); \ if (t > 16) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(e, a, b, c, d, me2, 16); \ if (t > 15) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(a, b, c, d, e, me2, 15); \ if (t > 14) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(b, c, d, e, a, me2, 14); \ if (t > 13) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(c, d, e, a, b, me2, 13); \ if (t > 12) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(d, e, a, b, c, me2, 12); \ if (t > 11) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(e, a, b, c, d, me2, 11); \ if (t > 10) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(a, b, c, d, e, me2, 10); \ if (t > 9) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(b, c, d, e, a, me2, 9); \ if (t > 8) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(c, d, e, a, b, me2, 8); \ if (t > 7) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(d, e, a, b, c, me2, 7); \ if (t > 6) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(e, a, b, c, d, me2, 6); \ if (t > 5) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(a, b, c, d, e, me2, 5); \ if (t > 4) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(b, c, d, e, a, me2, 4); \ if (t > 3) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(c, d, e, a, b, me2, 3); \ if (t > 2) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(d, e, a, b, c, me2, 2); \ if (t > 1) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(e, a, b, c, d, me2, 1); \ if (t > 0) HASHCLASH_SHA1COMPRESS_ROUND1_STEP_BW(a, b, c, d, e, me2, 0); \ ihvin[0] = a; ihvin[1] = b; ihvin[2] = c; ihvin[3] = d; ihvin[4] = e; \ a = state[0]; b = state[1]; c = state[2]; d = state[3]; e = state[4]; \ if (t <= 0) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, me2, 0); \ if (t <= 1) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, me2, 1); \ if (t <= 2) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, me2, 2); \ if (t <= 3) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, me2, 3); \ if (t <= 4) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, me2, 4); \ if (t <= 5) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, me2, 5); \ if (t <= 6) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, me2, 6); \ if (t <= 7) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, me2, 7); \ if (t <= 8) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, me2, 8); \ if (t <= 9) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, me2, 9); \ if (t <= 10) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, me2, 10); \ if (t <= 11) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, me2, 11); \ if (t <= 12) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, me2, 12); \ if (t <= 13) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, me2, 13); \ if (t <= 14) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, me2, 14); \ if (t <= 15) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(a, b, c, d, e, me2, 15); \ if (t <= 16) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(e, a, b, c, d, me2, 16); \ if (t <= 17) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(d, e, a, b, c, me2, 17); \ if (t <= 18) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(c, d, e, a, b, me2, 18); \ if (t <= 19) HASHCLASH_SHA1COMPRESS_ROUND1_STEP(b, c, d, e, a, me2, 19); \ if (t <= 20) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, me2, 20); \ if (t <= 21) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, me2, 21); \ if (t <= 22) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, me2, 22); \ if (t <= 23) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, me2, 23); \ if (t <= 24) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, me2, 24); \ if (t <= 25) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, me2, 25); \ if (t <= 26) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, me2, 26); \ if (t <= 27) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, me2, 27); \ if (t <= 28) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, me2, 28); \ if (t <= 29) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, me2, 29); \ if (t <= 30) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, me2, 30); \ if (t <= 31) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, me2, 31); \ if (t <= 32) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, me2, 32); \ if (t <= 33) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, me2, 33); \ if (t <= 34) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, me2, 34); \ if (t <= 35) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(a, b, c, d, e, me2, 35); \ if (t <= 36) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(e, a, b, c, d, me2, 36); \ if (t <= 37) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(d, e, a, b, c, me2, 37); \ if (t <= 38) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(c, d, e, a, b, me2, 38); \ if (t <= 39) HASHCLASH_SHA1COMPRESS_ROUND2_STEP(b, c, d, e, a, me2, 39); \ if (t <= 40) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, me2, 40); \ if (t <= 41) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, me2, 41); \ if (t <= 42) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, me2, 42); \ if (t <= 43) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, me2, 43); \ if (t <= 44) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, me2, 44); \ if (t <= 45) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, me2, 45); \ if (t <= 46) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, me2, 46); \ if (t <= 47) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, me2, 47); \ if (t <= 48) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, me2, 48); \ if (t <= 49) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, me2, 49); \ if (t <= 50) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, me2, 50); \ if (t <= 51) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, me2, 51); \ if (t <= 52) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, me2, 52); \ if (t <= 53) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, me2, 53); \ if (t <= 54) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, me2, 54); \ if (t <= 55) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(a, b, c, d, e, me2, 55); \ if (t <= 56) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(e, a, b, c, d, me2, 56); \ if (t <= 57) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(d, e, a, b, c, me2, 57); \ if (t <= 58) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(c, d, e, a, b, me2, 58); \ if (t <= 59) HASHCLASH_SHA1COMPRESS_ROUND3_STEP(b, c, d, e, a, me2, 59); \ if (t <= 60) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, me2, 60); \ if (t <= 61) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, me2, 61); \ if (t <= 62) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, me2, 62); \ if (t <= 63) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, me2, 63); \ if (t <= 64) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, me2, 64); \ if (t <= 65) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, me2, 65); \ if (t <= 66) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, me2, 66); \ if (t <= 67) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, me2, 67); \ if (t <= 68) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, me2, 68); \ if (t <= 69) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, me2, 69); \ if (t <= 70) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, me2, 70); \ if (t <= 71) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, me2, 71); \ if (t <= 72) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, me2, 72); \ if (t <= 73) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, me2, 73); \ if (t <= 74) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, me2, 74); \ if (t <= 75) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(a, b, c, d, e, me2, 75); \ if (t <= 76) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(e, a, b, c, d, me2, 76); \ if (t <= 77) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(d, e, a, b, c, me2, 77); \ if (t <= 78) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(c, d, e, a, b, me2, 78); \ if (t <= 79) HASHCLASH_SHA1COMPRESS_ROUND4_STEP(b, c, d, e, a, me2, 79); \ ihvout[0] = ihvin[0] + a; ihvout[1] = ihvin[1] + b; ihvout[2] = ihvin[2] + c; ihvout[3] = ihvin[3] + d; ihvout[4] = ihvin[4] + e; \ } #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4127) /* Compiler complains about the checks in the above macro being constant. */ #endif #ifdef DOSTORESTATE0 SHA1_RECOMPRESS(0) #endif #ifdef DOSTORESTATE1 SHA1_RECOMPRESS(1) #endif #ifdef DOSTORESTATE2 SHA1_RECOMPRESS(2) #endif #ifdef DOSTORESTATE3 SHA1_RECOMPRESS(3) #endif #ifdef DOSTORESTATE4 SHA1_RECOMPRESS(4) #endif #ifdef DOSTORESTATE5 SHA1_RECOMPRESS(5) #endif #ifdef DOSTORESTATE6 SHA1_RECOMPRESS(6) #endif #ifdef DOSTORESTATE7 SHA1_RECOMPRESS(7) #endif #ifdef DOSTORESTATE8 SHA1_RECOMPRESS(8) #endif #ifdef DOSTORESTATE9 SHA1_RECOMPRESS(9) #endif #ifdef DOSTORESTATE10 SHA1_RECOMPRESS(10) #endif #ifdef DOSTORESTATE11 SHA1_RECOMPRESS(11) #endif #ifdef DOSTORESTATE12 SHA1_RECOMPRESS(12) #endif #ifdef DOSTORESTATE13 SHA1_RECOMPRESS(13) #endif #ifdef DOSTORESTATE14 SHA1_RECOMPRESS(14) #endif #ifdef DOSTORESTATE15 SHA1_RECOMPRESS(15) #endif #ifdef DOSTORESTATE16 SHA1_RECOMPRESS(16) #endif #ifdef DOSTORESTATE17 SHA1_RECOMPRESS(17) #endif #ifdef DOSTORESTATE18 SHA1_RECOMPRESS(18) #endif #ifdef DOSTORESTATE19 SHA1_RECOMPRESS(19) #endif #ifdef DOSTORESTATE20 SHA1_RECOMPRESS(20) #endif #ifdef DOSTORESTATE21 SHA1_RECOMPRESS(21) #endif #ifdef DOSTORESTATE22 SHA1_RECOMPRESS(22) #endif #ifdef DOSTORESTATE23 SHA1_RECOMPRESS(23) #endif #ifdef DOSTORESTATE24 SHA1_RECOMPRESS(24) #endif #ifdef DOSTORESTATE25 SHA1_RECOMPRESS(25) #endif #ifdef DOSTORESTATE26 SHA1_RECOMPRESS(26) #endif #ifdef DOSTORESTATE27 SHA1_RECOMPRESS(27) #endif #ifdef DOSTORESTATE28 SHA1_RECOMPRESS(28) #endif #ifdef DOSTORESTATE29 SHA1_RECOMPRESS(29) #endif #ifdef DOSTORESTATE30 SHA1_RECOMPRESS(30) #endif #ifdef DOSTORESTATE31 SHA1_RECOMPRESS(31) #endif #ifdef DOSTORESTATE32 SHA1_RECOMPRESS(32) #endif #ifdef DOSTORESTATE33 SHA1_RECOMPRESS(33) #endif #ifdef DOSTORESTATE34 SHA1_RECOMPRESS(34) #endif #ifdef DOSTORESTATE35 SHA1_RECOMPRESS(35) #endif #ifdef DOSTORESTATE36 SHA1_RECOMPRESS(36) #endif #ifdef DOSTORESTATE37 SHA1_RECOMPRESS(37) #endif #ifdef DOSTORESTATE38 SHA1_RECOMPRESS(38) #endif #ifdef DOSTORESTATE39 SHA1_RECOMPRESS(39) #endif #ifdef DOSTORESTATE40 SHA1_RECOMPRESS(40) #endif #ifdef DOSTORESTATE41 SHA1_RECOMPRESS(41) #endif #ifdef DOSTORESTATE42 SHA1_RECOMPRESS(42) #endif #ifdef DOSTORESTATE43 SHA1_RECOMPRESS(43) #endif #ifdef DOSTORESTATE44 SHA1_RECOMPRESS(44) #endif #ifdef DOSTORESTATE45 SHA1_RECOMPRESS(45) #endif #ifdef DOSTORESTATE46 SHA1_RECOMPRESS(46) #endif #ifdef DOSTORESTATE47 SHA1_RECOMPRESS(47) #endif #ifdef DOSTORESTATE48 SHA1_RECOMPRESS(48) #endif #ifdef DOSTORESTATE49 SHA1_RECOMPRESS(49) #endif #ifdef DOSTORESTATE50 SHA1_RECOMPRESS(50) #endif #ifdef DOSTORESTATE51 SHA1_RECOMPRESS(51) #endif #ifdef DOSTORESTATE52 SHA1_RECOMPRESS(52) #endif #ifdef DOSTORESTATE53 SHA1_RECOMPRESS(53) #endif #ifdef DOSTORESTATE54 SHA1_RECOMPRESS(54) #endif #ifdef DOSTORESTATE55 SHA1_RECOMPRESS(55) #endif #ifdef DOSTORESTATE56 SHA1_RECOMPRESS(56) #endif #ifdef DOSTORESTATE57 SHA1_RECOMPRESS(57) #endif #ifdef DOSTORESTATE58 SHA1_RECOMPRESS(58) #endif #ifdef DOSTORESTATE59 SHA1_RECOMPRESS(59) #endif #ifdef DOSTORESTATE60 SHA1_RECOMPRESS(60) #endif #ifdef DOSTORESTATE61 SHA1_RECOMPRESS(61) #endif #ifdef DOSTORESTATE62 SHA1_RECOMPRESS(62) #endif #ifdef DOSTORESTATE63 SHA1_RECOMPRESS(63) #endif #ifdef DOSTORESTATE64 SHA1_RECOMPRESS(64) #endif #ifdef DOSTORESTATE65 SHA1_RECOMPRESS(65) #endif #ifdef DOSTORESTATE66 SHA1_RECOMPRESS(66) #endif #ifdef DOSTORESTATE67 SHA1_RECOMPRESS(67) #endif #ifdef DOSTORESTATE68 SHA1_RECOMPRESS(68) #endif #ifdef DOSTORESTATE69 SHA1_RECOMPRESS(69) #endif #ifdef DOSTORESTATE70 SHA1_RECOMPRESS(70) #endif #ifdef DOSTORESTATE71 SHA1_RECOMPRESS(71) #endif #ifdef DOSTORESTATE72 SHA1_RECOMPRESS(72) #endif #ifdef DOSTORESTATE73 SHA1_RECOMPRESS(73) #endif #ifdef DOSTORESTATE74 SHA1_RECOMPRESS(74) #endif #ifdef DOSTORESTATE75 SHA1_RECOMPRESS(75) #endif #ifdef DOSTORESTATE76 SHA1_RECOMPRESS(76) #endif #ifdef DOSTORESTATE77 SHA1_RECOMPRESS(77) #endif #ifdef DOSTORESTATE78 SHA1_RECOMPRESS(78) #endif #ifdef DOSTORESTATE79 SHA1_RECOMPRESS(79) #endif #ifdef _MSC_VER #pragma warning(pop) #endif static void sha1_recompression_step(uint32_t step, uint32_t ihvin[5], uint32_t ihvout[5], const uint32_t me2[80], const uint32_t state[5]) { switch (step) { #ifdef DOSTORESTATE0 case 0: sha1recompress_fast_0(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE1 case 1: sha1recompress_fast_1(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE2 case 2: sha1recompress_fast_2(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE3 case 3: sha1recompress_fast_3(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE4 case 4: sha1recompress_fast_4(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE5 case 5: sha1recompress_fast_5(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE6 case 6: sha1recompress_fast_6(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE7 case 7: sha1recompress_fast_7(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE8 case 8: sha1recompress_fast_8(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE9 case 9: sha1recompress_fast_9(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE10 case 10: sha1recompress_fast_10(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE11 case 11: sha1recompress_fast_11(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE12 case 12: sha1recompress_fast_12(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE13 case 13: sha1recompress_fast_13(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE14 case 14: sha1recompress_fast_14(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE15 case 15: sha1recompress_fast_15(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE16 case 16: sha1recompress_fast_16(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE17 case 17: sha1recompress_fast_17(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE18 case 18: sha1recompress_fast_18(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE19 case 19: sha1recompress_fast_19(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE20 case 20: sha1recompress_fast_20(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE21 case 21: sha1recompress_fast_21(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE22 case 22: sha1recompress_fast_22(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE23 case 23: sha1recompress_fast_23(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE24 case 24: sha1recompress_fast_24(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE25 case 25: sha1recompress_fast_25(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE26 case 26: sha1recompress_fast_26(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE27 case 27: sha1recompress_fast_27(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE28 case 28: sha1recompress_fast_28(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE29 case 29: sha1recompress_fast_29(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE30 case 30: sha1recompress_fast_30(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE31 case 31: sha1recompress_fast_31(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE32 case 32: sha1recompress_fast_32(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE33 case 33: sha1recompress_fast_33(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE34 case 34: sha1recompress_fast_34(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE35 case 35: sha1recompress_fast_35(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE36 case 36: sha1recompress_fast_36(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE37 case 37: sha1recompress_fast_37(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE38 case 38: sha1recompress_fast_38(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE39 case 39: sha1recompress_fast_39(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE40 case 40: sha1recompress_fast_40(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE41 case 41: sha1recompress_fast_41(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE42 case 42: sha1recompress_fast_42(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE43 case 43: sha1recompress_fast_43(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE44 case 44: sha1recompress_fast_44(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE45 case 45: sha1recompress_fast_45(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE46 case 46: sha1recompress_fast_46(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE47 case 47: sha1recompress_fast_47(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE48 case 48: sha1recompress_fast_48(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE49 case 49: sha1recompress_fast_49(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE50 case 50: sha1recompress_fast_50(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE51 case 51: sha1recompress_fast_51(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE52 case 52: sha1recompress_fast_52(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE53 case 53: sha1recompress_fast_53(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE54 case 54: sha1recompress_fast_54(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE55 case 55: sha1recompress_fast_55(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE56 case 56: sha1recompress_fast_56(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE57 case 57: sha1recompress_fast_57(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE58 case 58: sha1recompress_fast_58(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE59 case 59: sha1recompress_fast_59(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE60 case 60: sha1recompress_fast_60(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE61 case 61: sha1recompress_fast_61(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE62 case 62: sha1recompress_fast_62(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE63 case 63: sha1recompress_fast_63(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE64 case 64: sha1recompress_fast_64(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE65 case 65: sha1recompress_fast_65(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE66 case 66: sha1recompress_fast_66(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE67 case 67: sha1recompress_fast_67(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE68 case 68: sha1recompress_fast_68(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE69 case 69: sha1recompress_fast_69(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE70 case 70: sha1recompress_fast_70(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE71 case 71: sha1recompress_fast_71(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE72 case 72: sha1recompress_fast_72(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE73 case 73: sha1recompress_fast_73(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE74 case 74: sha1recompress_fast_74(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE75 case 75: sha1recompress_fast_75(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE76 case 76: sha1recompress_fast_76(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE77 case 77: sha1recompress_fast_77(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE78 case 78: sha1recompress_fast_78(ihvin, ihvout, me2, state); break; #endif #ifdef DOSTORESTATE79 case 79: sha1recompress_fast_79(ihvin, ihvout, me2, state); break; #endif default: abort(); } } static void sha1_process(SHA1_CTX *ctx, const uint32_t block[16]) { unsigned i, j; uint32_t ubc_dv_mask[DVMASKSIZE] = { 0xFFFFFFFF }; uint32_t ihvtmp[5]; ctx->ihv1[0] = ctx->ihv[0]; ctx->ihv1[1] = ctx->ihv[1]; ctx->ihv1[2] = ctx->ihv[2]; ctx->ihv1[3] = ctx->ihv[3]; ctx->ihv1[4] = ctx->ihv[4]; sha1_compression_states(ctx->ihv, block, ctx->m1, ctx->states); if (ctx->detect_coll) { if (ctx->ubc_check) { ubc_check(ctx->m1, ubc_dv_mask); } if (ubc_dv_mask[0] != 0) { for (i = 0; sha1_dvs[i].dvType != 0; ++i) { if (ubc_dv_mask[0] & ((uint32_t)(1) << sha1_dvs[i].maskb)) { for (j = 0; j < 80; ++j) ctx->m2[j] = ctx->m1[j] ^ sha1_dvs[i].dm[j]; sha1_recompression_step(sha1_dvs[i].testt, ctx->ihv2, ihvtmp, ctx->m2, ctx->states[sha1_dvs[i].testt]); /* to verify SHA-1 collision detection code with collisions for reduced-step SHA-1 */ if ((0 == ((ihvtmp[0] ^ ctx->ihv[0]) | (ihvtmp[1] ^ ctx->ihv[1]) | (ihvtmp[2] ^ ctx->ihv[2]) | (ihvtmp[3] ^ ctx->ihv[3]) | (ihvtmp[4] ^ ctx->ihv[4]))) || (ctx->reduced_round_coll && 0==((ctx->ihv1[0] ^ ctx->ihv2[0]) | (ctx->ihv1[1] ^ ctx->ihv2[1]) | (ctx->ihv1[2] ^ ctx->ihv2[2]) | (ctx->ihv1[3] ^ ctx->ihv2[3]) | (ctx->ihv1[4] ^ ctx->ihv2[4])))) { ctx->found_collision = 1; if (ctx->safe_hash) { sha1_compression_W(ctx->ihv, ctx->m1); sha1_compression_W(ctx->ihv, ctx->m1); } break; } } } } } } void SHA1DCInit(SHA1_CTX *ctx) { ctx->total = 0; ctx->ihv[0] = 0x67452301; ctx->ihv[1] = 0xEFCDAB89; ctx->ihv[2] = 0x98BADCFE; ctx->ihv[3] = 0x10325476; ctx->ihv[4] = 0xC3D2E1F0; ctx->found_collision = 0; ctx->safe_hash = SHA1DC_INIT_SAFE_HASH_DEFAULT; ctx->ubc_check = 1; ctx->detect_coll = 1; ctx->reduced_round_coll = 0; ctx->callback = NULL; } void SHA1DCSetSafeHash(SHA1_CTX *ctx, int safehash) { if (safehash) ctx->safe_hash = 1; else ctx->safe_hash = 0; } void SHA1DCSetUseUBC(SHA1_CTX *ctx, int ubc_check) { if (ubc_check) ctx->ubc_check = 1; else ctx->ubc_check = 0; } void SHA1DCSetUseDetectColl(SHA1_CTX *ctx, int detect_coll) { if (detect_coll) ctx->detect_coll = 1; else ctx->detect_coll = 0; } void SHA1DCSetDetectReducedRoundCollision(SHA1_CTX *ctx, int reduced_round_coll) { if (reduced_round_coll) ctx->reduced_round_coll = 1; else ctx->reduced_round_coll = 0; } void SHA1DCSetCallback(SHA1_CTX *ctx, collision_block_callback callback) { ctx->callback = callback; } void SHA1DCUpdate(SHA1_CTX *ctx, const char *buf, size_t len) { unsigned left, fill; if (len == 0) return; left = ctx->total & 63; fill = 64 - left; if (left && len >= fill) { ctx->total += fill; memcpy(ctx->buffer + left, buf, fill); sha1_process(ctx, (uint32_t*)(ctx->buffer)); buf += fill; len -= fill; left = 0; } while (len >= 64) { ctx->total += 64; #if defined(SHA1DC_ALLOW_UNALIGNED_ACCESS) sha1_process(ctx, (uint32_t*)(buf)); #else memcpy(ctx->buffer, buf, 64); sha1_process(ctx, (uint32_t*)(ctx->buffer)); #endif /* defined(SHA1DC_ALLOW_UNALIGNED_ACCESS) */ buf += 64; len -= 64; } if (len > 0) { ctx->total += len; memcpy(ctx->buffer + left, buf, len); } } static const unsigned char sha1_padding[64] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int SHA1DCFinal(unsigned char output[20], SHA1_CTX *ctx) { uint32_t last = ctx->total & 63; uint32_t padn = (last < 56) ? (56 - last) : (120 - last); uint64_t total; SHA1DCUpdate(ctx, (const char*)(sha1_padding), padn); total = ctx->total - padn; total <<= 3; ctx->buffer[56] = (unsigned char)(total >> 56); ctx->buffer[57] = (unsigned char)(total >> 48); ctx->buffer[58] = (unsigned char)(total >> 40); ctx->buffer[59] = (unsigned char)(total >> 32); ctx->buffer[60] = (unsigned char)(total >> 24); ctx->buffer[61] = (unsigned char)(total >> 16); ctx->buffer[62] = (unsigned char)(total >> 8); ctx->buffer[63] = (unsigned char)(total); sha1_process(ctx, (uint32_t*)(ctx->buffer)); output[0] = (unsigned char)(ctx->ihv[0] >> 24); output[1] = (unsigned char)(ctx->ihv[0] >> 16); output[2] = (unsigned char)(ctx->ihv[0] >> 8); output[3] = (unsigned char)(ctx->ihv[0]); output[4] = (unsigned char)(ctx->ihv[1] >> 24); output[5] = (unsigned char)(ctx->ihv[1] >> 16); output[6] = (unsigned char)(ctx->ihv[1] >> 8); output[7] = (unsigned char)(ctx->ihv[1]); output[8] = (unsigned char)(ctx->ihv[2] >> 24); output[9] = (unsigned char)(ctx->ihv[2] >> 16); output[10] = (unsigned char)(ctx->ihv[2] >> 8); output[11] = (unsigned char)(ctx->ihv[2]); output[12] = (unsigned char)(ctx->ihv[3] >> 24); output[13] = (unsigned char)(ctx->ihv[3] >> 16); output[14] = (unsigned char)(ctx->ihv[3] >> 8); output[15] = (unsigned char)(ctx->ihv[3]); output[16] = (unsigned char)(ctx->ihv[4] >> 24); output[17] = (unsigned char)(ctx->ihv[4] >> 16); output[18] = (unsigned char)(ctx->ihv[4] >> 8); output[19] = (unsigned char)(ctx->ihv[4]); return ctx->found_collision; } #ifdef SHA1DC_CUSTOM_TRAILING_INCLUDE_SHA1_C #include SHA1DC_CUSTOM_TRAILING_INCLUDE_SHA1_C #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash/sha1
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash/sha1/sha1dc/ubc_check.c
/*** * Copyright 2017 Marc Stevens <[email protected]>, Dan Shumow <[email protected]> * Distributed under the MIT Software License. * See accompanying file LICENSE.txt or copy at * https://opensource.org/licenses/MIT ***/ /* // this file was generated by the 'parse_bitrel' program in the tools section // using the data files from directory 'tools/data/3565' // // sha1_dvs contains a list of SHA-1 Disturbance Vectors (DV) to check // dvType, dvK and dvB define the DV: I(K,B) or II(K,B) (see the paper) // dm[80] is the expanded message block XOR-difference defined by the DV // testt is the step to do the recompression from for collision detection // maski and maskb define the bit to check for each DV in the dvmask returned by ubc_check // // ubc_check takes as input an expanded message block and verifies the unavoidable bitconditions for all listed DVs // it returns a dvmask where each bit belonging to a DV is set if all unavoidable bitconditions for that DV have been met // thus one needs to do the recompression check for each DV that has its bit set // // ubc_check is programmatically generated and the unavoidable bitconditions have been hardcoded // a directly verifiable version named ubc_check_verify can be found in ubc_check_verify.c // ubc_check has been verified against ubc_check_verify using the 'ubc_check_test' program in the tools section */ #ifndef SHA1DC_NO_STANDARD_INCLUDES #include <stdint.h> #endif #ifdef SHA1DC_CUSTOM_INCLUDE_UBC_CHECK_C #include SHA1DC_CUSTOM_INCLUDE_UBC_CHECK_C #endif #include "ubc_check.h" static const uint32_t DV_I_43_0_bit = (uint32_t)(1) << 0; static const uint32_t DV_I_44_0_bit = (uint32_t)(1) << 1; static const uint32_t DV_I_45_0_bit = (uint32_t)(1) << 2; static const uint32_t DV_I_46_0_bit = (uint32_t)(1) << 3; static const uint32_t DV_I_46_2_bit = (uint32_t)(1) << 4; static const uint32_t DV_I_47_0_bit = (uint32_t)(1) << 5; static const uint32_t DV_I_47_2_bit = (uint32_t)(1) << 6; static const uint32_t DV_I_48_0_bit = (uint32_t)(1) << 7; static const uint32_t DV_I_48_2_bit = (uint32_t)(1) << 8; static const uint32_t DV_I_49_0_bit = (uint32_t)(1) << 9; static const uint32_t DV_I_49_2_bit = (uint32_t)(1) << 10; static const uint32_t DV_I_50_0_bit = (uint32_t)(1) << 11; static const uint32_t DV_I_50_2_bit = (uint32_t)(1) << 12; static const uint32_t DV_I_51_0_bit = (uint32_t)(1) << 13; static const uint32_t DV_I_51_2_bit = (uint32_t)(1) << 14; static const uint32_t DV_I_52_0_bit = (uint32_t)(1) << 15; static const uint32_t DV_II_45_0_bit = (uint32_t)(1) << 16; static const uint32_t DV_II_46_0_bit = (uint32_t)(1) << 17; static const uint32_t DV_II_46_2_bit = (uint32_t)(1) << 18; static const uint32_t DV_II_47_0_bit = (uint32_t)(1) << 19; static const uint32_t DV_II_48_0_bit = (uint32_t)(1) << 20; static const uint32_t DV_II_49_0_bit = (uint32_t)(1) << 21; static const uint32_t DV_II_49_2_bit = (uint32_t)(1) << 22; static const uint32_t DV_II_50_0_bit = (uint32_t)(1) << 23; static const uint32_t DV_II_50_2_bit = (uint32_t)(1) << 24; static const uint32_t DV_II_51_0_bit = (uint32_t)(1) << 25; static const uint32_t DV_II_51_2_bit = (uint32_t)(1) << 26; static const uint32_t DV_II_52_0_bit = (uint32_t)(1) << 27; static const uint32_t DV_II_53_0_bit = (uint32_t)(1) << 28; static const uint32_t DV_II_54_0_bit = (uint32_t)(1) << 29; static const uint32_t DV_II_55_0_bit = (uint32_t)(1) << 30; static const uint32_t DV_II_56_0_bit = (uint32_t)(1) << 31; dv_info_t sha1_dvs[] = { {1,43,0,58,0,0, { 0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408,0x800000e6,0x8000004c,0x00000803,0x80000161,0x80000599 } } , {1,44,0,58,0,1, { 0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408,0x800000e6,0x8000004c,0x00000803,0x80000161 } } , {1,45,0,58,0,2, { 0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408,0x800000e6,0x8000004c,0x00000803 } } , {1,46,0,58,0,3, { 0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408,0x800000e6,0x8000004c } } , {1,46,2,58,0,4, { 0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a,0x00000060,0x00000590,0x00001020,0x0000039a,0x00000132 } } , {1,47,0,58,0,5, { 0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408,0x800000e6 } } , {1,47,2,58,0,6, { 0x20000043,0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a,0x00000060,0x00000590,0x00001020,0x0000039a } } , {1,48,0,58,0,7, { 0xb800000a,0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408 } } , {1,48,2,58,0,8, { 0xe000002a,0x20000043,0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a,0x00000060,0x00000590,0x00001020 } } , {1,49,0,58,0,9, { 0x18000000,0xb800000a,0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164 } } , {1,49,2,58,0,10, { 0x60000000,0xe000002a,0x20000043,0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a,0x00000060,0x00000590 } } , {1,50,0,65,0,11, { 0x0800000c,0x18000000,0xb800000a,0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018 } } , {1,50,2,65,0,12, { 0x20000030,0x60000000,0xe000002a,0x20000043,0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a,0x00000060 } } , {1,51,0,65,0,13, { 0xe8000000,0x0800000c,0x18000000,0xb800000a,0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202 } } , {1,51,2,65,0,14, { 0xa0000003,0x20000030,0x60000000,0xe000002a,0x20000043,0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a } } , {1,52,0,65,0,15, { 0x04000010,0xe8000000,0x0800000c,0x18000000,0xb800000a,0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012 } } , {2,45,0,58,0,16, { 0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b,0x8000016d,0x8000041a,0x000002e4,0x80000054,0x00000967 } } , {2,46,0,58,0,17, { 0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b,0x8000016d,0x8000041a,0x000002e4,0x80000054 } } , {2,46,2,58,0,18, { 0x90000070,0xb0000053,0x30000008,0x00000043,0xd0000072,0xb0000010,0xf0000062,0xc0000042,0x00000030,0xe0000042,0x20000060,0xe0000041,0x20000050,0xc0000041,0xe0000072,0xa0000003,0xc0000012,0x60000041,0xc0000032,0x20000001,0xc0000002,0xe0000042,0x60000042,0x80000002,0x00000000,0x00000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000001,0x00000060,0x80000003,0x40000002,0xc0000040,0xc0000002,0x80000000,0x80000000,0x80000002,0x00000040,0x00000002,0x80000000,0x80000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000105,0x00000089,0x00000016,0x0000020b,0x0000011b,0x0000012d,0x0000041e,0x00000224,0x00000050,0x0000092e,0x0000046c,0x000005b6,0x0000106a,0x00000b90,0x00000152 } } , {2,47,0,58,0,19, { 0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b,0x8000016d,0x8000041a,0x000002e4 } } , {2,48,0,58,0,20, { 0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b,0x8000016d,0x8000041a } } , {2,49,0,58,0,21, { 0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b,0x8000016d } } , {2,49,2,58,0,22, { 0xf0000010,0xf000006a,0x80000040,0x90000070,0xb0000053,0x30000008,0x00000043,0xd0000072,0xb0000010,0xf0000062,0xc0000042,0x00000030,0xe0000042,0x20000060,0xe0000041,0x20000050,0xc0000041,0xe0000072,0xa0000003,0xc0000012,0x60000041,0xc0000032,0x20000001,0xc0000002,0xe0000042,0x60000042,0x80000002,0x00000000,0x00000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000001,0x00000060,0x80000003,0x40000002,0xc0000040,0xc0000002,0x80000000,0x80000000,0x80000002,0x00000040,0x00000002,0x80000000,0x80000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000105,0x00000089,0x00000016,0x0000020b,0x0000011b,0x0000012d,0x0000041e,0x00000224,0x00000050,0x0000092e,0x0000046c,0x000005b6 } } , {2,50,0,65,0,23, { 0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b } } , {2,50,2,65,0,24, { 0xd0000072,0xf0000010,0xf000006a,0x80000040,0x90000070,0xb0000053,0x30000008,0x00000043,0xd0000072,0xb0000010,0xf0000062,0xc0000042,0x00000030,0xe0000042,0x20000060,0xe0000041,0x20000050,0xc0000041,0xe0000072,0xa0000003,0xc0000012,0x60000041,0xc0000032,0x20000001,0xc0000002,0xe0000042,0x60000042,0x80000002,0x00000000,0x00000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000001,0x00000060,0x80000003,0x40000002,0xc0000040,0xc0000002,0x80000000,0x80000000,0x80000002,0x00000040,0x00000002,0x80000000,0x80000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000105,0x00000089,0x00000016,0x0000020b,0x0000011b,0x0000012d,0x0000041e,0x00000224,0x00000050,0x0000092e,0x0000046c } } , {2,51,0,65,0,25, { 0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b } } , {2,51,2,65,0,26, { 0x00000043,0xd0000072,0xf0000010,0xf000006a,0x80000040,0x90000070,0xb0000053,0x30000008,0x00000043,0xd0000072,0xb0000010,0xf0000062,0xc0000042,0x00000030,0xe0000042,0x20000060,0xe0000041,0x20000050,0xc0000041,0xe0000072,0xa0000003,0xc0000012,0x60000041,0xc0000032,0x20000001,0xc0000002,0xe0000042,0x60000042,0x80000002,0x00000000,0x00000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000001,0x00000060,0x80000003,0x40000002,0xc0000040,0xc0000002,0x80000000,0x80000000,0x80000002,0x00000040,0x00000002,0x80000000,0x80000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000105,0x00000089,0x00000016,0x0000020b,0x0000011b,0x0000012d,0x0000041e,0x00000224,0x00000050,0x0000092e } } , {2,52,0,65,0,27, { 0x0c000002,0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014 } } , {2,53,0,65,0,28, { 0xcc000014,0x0c000002,0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089 } } , {2,54,0,65,0,29, { 0x0400001c,0xcc000014,0x0c000002,0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107 } } , {2,55,0,65,0,30, { 0x00000010,0x0400001c,0xcc000014,0x0c000002,0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b } } , {2,56,0,65,0,31, { 0x2600001a,0x00000010,0x0400001c,0xcc000014,0x0c000002,0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046 } } , {0,0,0,0,0,0, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}} }; void ubc_check(const uint32_t W[80], uint32_t dvmask[1]) { uint32_t mask = ~((uint32_t)(0)); mask &= (((((W[44]^W[45])>>29)&1)-1) | ~(DV_I_48_0_bit|DV_I_51_0_bit|DV_I_52_0_bit|DV_II_45_0_bit|DV_II_46_0_bit|DV_II_50_0_bit|DV_II_51_0_bit)); mask &= (((((W[49]^W[50])>>29)&1)-1) | ~(DV_I_46_0_bit|DV_II_45_0_bit|DV_II_50_0_bit|DV_II_51_0_bit|DV_II_55_0_bit|DV_II_56_0_bit)); mask &= (((((W[48]^W[49])>>29)&1)-1) | ~(DV_I_45_0_bit|DV_I_52_0_bit|DV_II_49_0_bit|DV_II_50_0_bit|DV_II_54_0_bit|DV_II_55_0_bit)); mask &= ((((W[47]^(W[50]>>25))&(1<<4))-(1<<4)) | ~(DV_I_47_0_bit|DV_I_49_0_bit|DV_I_51_0_bit|DV_II_45_0_bit|DV_II_51_0_bit|DV_II_56_0_bit)); mask &= (((((W[47]^W[48])>>29)&1)-1) | ~(DV_I_44_0_bit|DV_I_51_0_bit|DV_II_48_0_bit|DV_II_49_0_bit|DV_II_53_0_bit|DV_II_54_0_bit)); mask &= (((((W[46]>>4)^(W[49]>>29))&1)-1) | ~(DV_I_46_0_bit|DV_I_48_0_bit|DV_I_50_0_bit|DV_I_52_0_bit|DV_II_50_0_bit|DV_II_55_0_bit)); mask &= (((((W[46]^W[47])>>29)&1)-1) | ~(DV_I_43_0_bit|DV_I_50_0_bit|DV_II_47_0_bit|DV_II_48_0_bit|DV_II_52_0_bit|DV_II_53_0_bit)); mask &= (((((W[45]>>4)^(W[48]>>29))&1)-1) | ~(DV_I_45_0_bit|DV_I_47_0_bit|DV_I_49_0_bit|DV_I_51_0_bit|DV_II_49_0_bit|DV_II_54_0_bit)); mask &= (((((W[45]^W[46])>>29)&1)-1) | ~(DV_I_49_0_bit|DV_I_52_0_bit|DV_II_46_0_bit|DV_II_47_0_bit|DV_II_51_0_bit|DV_II_52_0_bit)); mask &= (((((W[44]>>4)^(W[47]>>29))&1)-1) | ~(DV_I_44_0_bit|DV_I_46_0_bit|DV_I_48_0_bit|DV_I_50_0_bit|DV_II_48_0_bit|DV_II_53_0_bit)); mask &= (((((W[43]>>4)^(W[46]>>29))&1)-1) | ~(DV_I_43_0_bit|DV_I_45_0_bit|DV_I_47_0_bit|DV_I_49_0_bit|DV_II_47_0_bit|DV_II_52_0_bit)); mask &= (((((W[43]^W[44])>>29)&1)-1) | ~(DV_I_47_0_bit|DV_I_50_0_bit|DV_I_51_0_bit|DV_II_45_0_bit|DV_II_49_0_bit|DV_II_50_0_bit)); mask &= (((((W[42]>>4)^(W[45]>>29))&1)-1) | ~(DV_I_44_0_bit|DV_I_46_0_bit|DV_I_48_0_bit|DV_I_52_0_bit|DV_II_46_0_bit|DV_II_51_0_bit)); mask &= (((((W[41]>>4)^(W[44]>>29))&1)-1) | ~(DV_I_43_0_bit|DV_I_45_0_bit|DV_I_47_0_bit|DV_I_51_0_bit|DV_II_45_0_bit|DV_II_50_0_bit)); mask &= (((((W[40]^W[41])>>29)&1)-1) | ~(DV_I_44_0_bit|DV_I_47_0_bit|DV_I_48_0_bit|DV_II_46_0_bit|DV_II_47_0_bit|DV_II_56_0_bit)); mask &= (((((W[54]^W[55])>>29)&1)-1) | ~(DV_I_51_0_bit|DV_II_47_0_bit|DV_II_50_0_bit|DV_II_55_0_bit|DV_II_56_0_bit)); mask &= (((((W[53]^W[54])>>29)&1)-1) | ~(DV_I_50_0_bit|DV_II_46_0_bit|DV_II_49_0_bit|DV_II_54_0_bit|DV_II_55_0_bit)); mask &= (((((W[52]^W[53])>>29)&1)-1) | ~(DV_I_49_0_bit|DV_II_45_0_bit|DV_II_48_0_bit|DV_II_53_0_bit|DV_II_54_0_bit)); mask &= ((((W[50]^(W[53]>>25))&(1<<4))-(1<<4)) | ~(DV_I_50_0_bit|DV_I_52_0_bit|DV_II_46_0_bit|DV_II_48_0_bit|DV_II_54_0_bit)); mask &= (((((W[50]^W[51])>>29)&1)-1) | ~(DV_I_47_0_bit|DV_II_46_0_bit|DV_II_51_0_bit|DV_II_52_0_bit|DV_II_56_0_bit)); mask &= ((((W[49]^(W[52]>>25))&(1<<4))-(1<<4)) | ~(DV_I_49_0_bit|DV_I_51_0_bit|DV_II_45_0_bit|DV_II_47_0_bit|DV_II_53_0_bit)); mask &= ((((W[48]^(W[51]>>25))&(1<<4))-(1<<4)) | ~(DV_I_48_0_bit|DV_I_50_0_bit|DV_I_52_0_bit|DV_II_46_0_bit|DV_II_52_0_bit)); mask &= (((((W[42]^W[43])>>29)&1)-1) | ~(DV_I_46_0_bit|DV_I_49_0_bit|DV_I_50_0_bit|DV_II_48_0_bit|DV_II_49_0_bit)); mask &= (((((W[41]^W[42])>>29)&1)-1) | ~(DV_I_45_0_bit|DV_I_48_0_bit|DV_I_49_0_bit|DV_II_47_0_bit|DV_II_48_0_bit)); mask &= (((((W[40]>>4)^(W[43]>>29))&1)-1) | ~(DV_I_44_0_bit|DV_I_46_0_bit|DV_I_50_0_bit|DV_II_49_0_bit|DV_II_56_0_bit)); mask &= (((((W[39]>>4)^(W[42]>>29))&1)-1) | ~(DV_I_43_0_bit|DV_I_45_0_bit|DV_I_49_0_bit|DV_II_48_0_bit|DV_II_55_0_bit)); if (mask & (DV_I_44_0_bit|DV_I_48_0_bit|DV_II_47_0_bit|DV_II_54_0_bit|DV_II_56_0_bit)) mask &= (((((W[38]>>4)^(W[41]>>29))&1)-1) | ~(DV_I_44_0_bit|DV_I_48_0_bit|DV_II_47_0_bit|DV_II_54_0_bit|DV_II_56_0_bit)); mask &= (((((W[37]>>4)^(W[40]>>29))&1)-1) | ~(DV_I_43_0_bit|DV_I_47_0_bit|DV_II_46_0_bit|DV_II_53_0_bit|DV_II_55_0_bit)); if (mask & (DV_I_52_0_bit|DV_II_48_0_bit|DV_II_51_0_bit|DV_II_56_0_bit)) mask &= (((((W[55]^W[56])>>29)&1)-1) | ~(DV_I_52_0_bit|DV_II_48_0_bit|DV_II_51_0_bit|DV_II_56_0_bit)); if (mask & (DV_I_52_0_bit|DV_II_48_0_bit|DV_II_50_0_bit|DV_II_56_0_bit)) mask &= ((((W[52]^(W[55]>>25))&(1<<4))-(1<<4)) | ~(DV_I_52_0_bit|DV_II_48_0_bit|DV_II_50_0_bit|DV_II_56_0_bit)); if (mask & (DV_I_51_0_bit|DV_II_47_0_bit|DV_II_49_0_bit|DV_II_55_0_bit)) mask &= ((((W[51]^(W[54]>>25))&(1<<4))-(1<<4)) | ~(DV_I_51_0_bit|DV_II_47_0_bit|DV_II_49_0_bit|DV_II_55_0_bit)); if (mask & (DV_I_48_0_bit|DV_II_47_0_bit|DV_II_52_0_bit|DV_II_53_0_bit)) mask &= (((((W[51]^W[52])>>29)&1)-1) | ~(DV_I_48_0_bit|DV_II_47_0_bit|DV_II_52_0_bit|DV_II_53_0_bit)); if (mask & (DV_I_46_0_bit|DV_I_49_0_bit|DV_II_45_0_bit|DV_II_48_0_bit)) mask &= (((((W[36]>>4)^(W[40]>>29))&1)-1) | ~(DV_I_46_0_bit|DV_I_49_0_bit|DV_II_45_0_bit|DV_II_48_0_bit)); if (mask & (DV_I_52_0_bit|DV_II_48_0_bit|DV_II_49_0_bit)) mask &= ((0-(((W[53]^W[56])>>29)&1)) | ~(DV_I_52_0_bit|DV_II_48_0_bit|DV_II_49_0_bit)); if (mask & (DV_I_50_0_bit|DV_II_46_0_bit|DV_II_47_0_bit)) mask &= ((0-(((W[51]^W[54])>>29)&1)) | ~(DV_I_50_0_bit|DV_II_46_0_bit|DV_II_47_0_bit)); if (mask & (DV_I_49_0_bit|DV_I_51_0_bit|DV_II_45_0_bit)) mask &= ((0-(((W[50]^W[52])>>29)&1)) | ~(DV_I_49_0_bit|DV_I_51_0_bit|DV_II_45_0_bit)); if (mask & (DV_I_48_0_bit|DV_I_50_0_bit|DV_I_52_0_bit)) mask &= ((0-(((W[49]^W[51])>>29)&1)) | ~(DV_I_48_0_bit|DV_I_50_0_bit|DV_I_52_0_bit)); if (mask & (DV_I_47_0_bit|DV_I_49_0_bit|DV_I_51_0_bit)) mask &= ((0-(((W[48]^W[50])>>29)&1)) | ~(DV_I_47_0_bit|DV_I_49_0_bit|DV_I_51_0_bit)); if (mask & (DV_I_46_0_bit|DV_I_48_0_bit|DV_I_50_0_bit)) mask &= ((0-(((W[47]^W[49])>>29)&1)) | ~(DV_I_46_0_bit|DV_I_48_0_bit|DV_I_50_0_bit)); if (mask & (DV_I_45_0_bit|DV_I_47_0_bit|DV_I_49_0_bit)) mask &= ((0-(((W[46]^W[48])>>29)&1)) | ~(DV_I_45_0_bit|DV_I_47_0_bit|DV_I_49_0_bit)); mask &= ((((W[45]^W[47])&(1<<6))-(1<<6)) | ~(DV_I_47_2_bit|DV_I_49_2_bit|DV_I_51_2_bit)); if (mask & (DV_I_44_0_bit|DV_I_46_0_bit|DV_I_48_0_bit)) mask &= ((0-(((W[45]^W[47])>>29)&1)) | ~(DV_I_44_0_bit|DV_I_46_0_bit|DV_I_48_0_bit)); mask &= (((((W[44]^W[46])>>6)&1)-1) | ~(DV_I_46_2_bit|DV_I_48_2_bit|DV_I_50_2_bit)); if (mask & (DV_I_43_0_bit|DV_I_45_0_bit|DV_I_47_0_bit)) mask &= ((0-(((W[44]^W[46])>>29)&1)) | ~(DV_I_43_0_bit|DV_I_45_0_bit|DV_I_47_0_bit)); mask &= ((0-((W[41]^(W[42]>>5))&(1<<1))) | ~(DV_I_48_2_bit|DV_II_46_2_bit|DV_II_51_2_bit)); mask &= ((0-((W[40]^(W[41]>>5))&(1<<1))) | ~(DV_I_47_2_bit|DV_I_51_2_bit|DV_II_50_2_bit)); if (mask & (DV_I_44_0_bit|DV_I_46_0_bit|DV_II_56_0_bit)) mask &= ((0-(((W[40]^W[42])>>4)&1)) | ~(DV_I_44_0_bit|DV_I_46_0_bit|DV_II_56_0_bit)); mask &= ((0-((W[39]^(W[40]>>5))&(1<<1))) | ~(DV_I_46_2_bit|DV_I_50_2_bit|DV_II_49_2_bit)); if (mask & (DV_I_43_0_bit|DV_I_45_0_bit|DV_II_55_0_bit)) mask &= ((0-(((W[39]^W[41])>>4)&1)) | ~(DV_I_43_0_bit|DV_I_45_0_bit|DV_II_55_0_bit)); if (mask & (DV_I_44_0_bit|DV_II_54_0_bit|DV_II_56_0_bit)) mask &= ((0-(((W[38]^W[40])>>4)&1)) | ~(DV_I_44_0_bit|DV_II_54_0_bit|DV_II_56_0_bit)); if (mask & (DV_I_43_0_bit|DV_II_53_0_bit|DV_II_55_0_bit)) mask &= ((0-(((W[37]^W[39])>>4)&1)) | ~(DV_I_43_0_bit|DV_II_53_0_bit|DV_II_55_0_bit)); mask &= ((0-((W[36]^(W[37]>>5))&(1<<1))) | ~(DV_I_47_2_bit|DV_I_50_2_bit|DV_II_46_2_bit)); if (mask & (DV_I_45_0_bit|DV_I_48_0_bit|DV_II_47_0_bit)) mask &= (((((W[35]>>4)^(W[39]>>29))&1)-1) | ~(DV_I_45_0_bit|DV_I_48_0_bit|DV_II_47_0_bit)); if (mask & (DV_I_48_0_bit|DV_II_48_0_bit)) mask &= ((0-((W[63]^(W[64]>>5))&(1<<0))) | ~(DV_I_48_0_bit|DV_II_48_0_bit)); if (mask & (DV_I_45_0_bit|DV_II_45_0_bit)) mask &= ((0-((W[63]^(W[64]>>5))&(1<<1))) | ~(DV_I_45_0_bit|DV_II_45_0_bit)); if (mask & (DV_I_47_0_bit|DV_II_47_0_bit)) mask &= ((0-((W[62]^(W[63]>>5))&(1<<0))) | ~(DV_I_47_0_bit|DV_II_47_0_bit)); if (mask & (DV_I_46_0_bit|DV_II_46_0_bit)) mask &= ((0-((W[61]^(W[62]>>5))&(1<<0))) | ~(DV_I_46_0_bit|DV_II_46_0_bit)); mask &= ((0-((W[61]^(W[62]>>5))&(1<<2))) | ~(DV_I_46_2_bit|DV_II_46_2_bit)); if (mask & (DV_I_45_0_bit|DV_II_45_0_bit)) mask &= ((0-((W[60]^(W[61]>>5))&(1<<0))) | ~(DV_I_45_0_bit|DV_II_45_0_bit)); if (mask & (DV_II_51_0_bit|DV_II_54_0_bit)) mask &= (((((W[58]^W[59])>>29)&1)-1) | ~(DV_II_51_0_bit|DV_II_54_0_bit)); if (mask & (DV_II_50_0_bit|DV_II_53_0_bit)) mask &= (((((W[57]^W[58])>>29)&1)-1) | ~(DV_II_50_0_bit|DV_II_53_0_bit)); if (mask & (DV_II_52_0_bit|DV_II_54_0_bit)) mask &= ((((W[56]^(W[59]>>25))&(1<<4))-(1<<4)) | ~(DV_II_52_0_bit|DV_II_54_0_bit)); if (mask & (DV_II_51_0_bit|DV_II_52_0_bit)) mask &= ((0-(((W[56]^W[59])>>29)&1)) | ~(DV_II_51_0_bit|DV_II_52_0_bit)); if (mask & (DV_II_49_0_bit|DV_II_52_0_bit)) mask &= (((((W[56]^W[57])>>29)&1)-1) | ~(DV_II_49_0_bit|DV_II_52_0_bit)); if (mask & (DV_II_51_0_bit|DV_II_53_0_bit)) mask &= ((((W[55]^(W[58]>>25))&(1<<4))-(1<<4)) | ~(DV_II_51_0_bit|DV_II_53_0_bit)); if (mask & (DV_II_50_0_bit|DV_II_52_0_bit)) mask &= ((((W[54]^(W[57]>>25))&(1<<4))-(1<<4)) | ~(DV_II_50_0_bit|DV_II_52_0_bit)); if (mask & (DV_II_49_0_bit|DV_II_51_0_bit)) mask &= ((((W[53]^(W[56]>>25))&(1<<4))-(1<<4)) | ~(DV_II_49_0_bit|DV_II_51_0_bit)); mask &= ((((W[51]^(W[50]>>5))&(1<<1))-(1<<1)) | ~(DV_I_50_2_bit|DV_II_46_2_bit)); mask &= ((((W[48]^W[50])&(1<<6))-(1<<6)) | ~(DV_I_50_2_bit|DV_II_46_2_bit)); if (mask & (DV_I_51_0_bit|DV_I_52_0_bit)) mask &= ((0-(((W[48]^W[55])>>29)&1)) | ~(DV_I_51_0_bit|DV_I_52_0_bit)); mask &= ((((W[47]^W[49])&(1<<6))-(1<<6)) | ~(DV_I_49_2_bit|DV_I_51_2_bit)); mask &= ((((W[48]^(W[47]>>5))&(1<<1))-(1<<1)) | ~(DV_I_47_2_bit|DV_II_51_2_bit)); mask &= ((((W[46]^W[48])&(1<<6))-(1<<6)) | ~(DV_I_48_2_bit|DV_I_50_2_bit)); mask &= ((((W[47]^(W[46]>>5))&(1<<1))-(1<<1)) | ~(DV_I_46_2_bit|DV_II_50_2_bit)); mask &= ((0-((W[44]^(W[45]>>5))&(1<<1))) | ~(DV_I_51_2_bit|DV_II_49_2_bit)); mask &= ((((W[43]^W[45])&(1<<6))-(1<<6)) | ~(DV_I_47_2_bit|DV_I_49_2_bit)); mask &= (((((W[42]^W[44])>>6)&1)-1) | ~(DV_I_46_2_bit|DV_I_48_2_bit)); mask &= ((((W[43]^(W[42]>>5))&(1<<1))-(1<<1)) | ~(DV_II_46_2_bit|DV_II_51_2_bit)); mask &= ((((W[42]^(W[41]>>5))&(1<<1))-(1<<1)) | ~(DV_I_51_2_bit|DV_II_50_2_bit)); mask &= ((((W[41]^(W[40]>>5))&(1<<1))-(1<<1)) | ~(DV_I_50_2_bit|DV_II_49_2_bit)); if (mask & (DV_I_52_0_bit|DV_II_51_0_bit)) mask &= ((((W[39]^(W[43]>>25))&(1<<4))-(1<<4)) | ~(DV_I_52_0_bit|DV_II_51_0_bit)); if (mask & (DV_I_51_0_bit|DV_II_50_0_bit)) mask &= ((((W[38]^(W[42]>>25))&(1<<4))-(1<<4)) | ~(DV_I_51_0_bit|DV_II_50_0_bit)); if (mask & (DV_I_48_2_bit|DV_I_51_2_bit)) mask &= ((0-((W[37]^(W[38]>>5))&(1<<1))) | ~(DV_I_48_2_bit|DV_I_51_2_bit)); if (mask & (DV_I_50_0_bit|DV_II_49_0_bit)) mask &= ((((W[37]^(W[41]>>25))&(1<<4))-(1<<4)) | ~(DV_I_50_0_bit|DV_II_49_0_bit)); if (mask & (DV_II_52_0_bit|DV_II_54_0_bit)) mask &= ((0-((W[36]^W[38])&(1<<4))) | ~(DV_II_52_0_bit|DV_II_54_0_bit)); mask &= ((0-((W[35]^(W[36]>>5))&(1<<1))) | ~(DV_I_46_2_bit|DV_I_49_2_bit)); if (mask & (DV_I_51_0_bit|DV_II_47_0_bit)) mask &= ((((W[35]^(W[39]>>25))&(1<<3))-(1<<3)) | ~(DV_I_51_0_bit|DV_II_47_0_bit)); if (mask) { if (mask & DV_I_43_0_bit) if ( !((W[61]^(W[62]>>5)) & (1<<1)) || !(!((W[59]^(W[63]>>25)) & (1<<5))) || !((W[58]^(W[63]>>30)) & (1<<0)) ) mask &= ~DV_I_43_0_bit; if (mask & DV_I_44_0_bit) if ( !((W[62]^(W[63]>>5)) & (1<<1)) || !(!((W[60]^(W[64]>>25)) & (1<<5))) || !((W[59]^(W[64]>>30)) & (1<<0)) ) mask &= ~DV_I_44_0_bit; if (mask & DV_I_46_2_bit) mask &= ((~((W[40]^W[42])>>2)) | ~DV_I_46_2_bit); if (mask & DV_I_47_2_bit) if ( !((W[62]^(W[63]>>5)) & (1<<2)) || !(!((W[41]^W[43]) & (1<<6))) ) mask &= ~DV_I_47_2_bit; if (mask & DV_I_48_2_bit) if ( !((W[63]^(W[64]>>5)) & (1<<2)) || !(!((W[48]^(W[49]<<5)) & (1<<6))) ) mask &= ~DV_I_48_2_bit; if (mask & DV_I_49_2_bit) if ( !(!((W[49]^(W[50]<<5)) & (1<<6))) || !((W[42]^W[50]) & (1<<1)) || !(!((W[39]^(W[40]<<5)) & (1<<6))) || !((W[38]^W[40]) & (1<<1)) ) mask &= ~DV_I_49_2_bit; if (mask & DV_I_50_0_bit) mask &= ((((W[36]^W[37])<<7)) | ~DV_I_50_0_bit); if (mask & DV_I_50_2_bit) mask &= ((((W[43]^W[51])<<11)) | ~DV_I_50_2_bit); if (mask & DV_I_51_0_bit) mask &= ((((W[37]^W[38])<<9)) | ~DV_I_51_0_bit); if (mask & DV_I_51_2_bit) if ( !(!((W[51]^(W[52]<<5)) & (1<<6))) || !(!((W[49]^W[51]) & (1<<6))) || !(!((W[37]^(W[37]>>5)) & (1<<1))) || !(!((W[35]^(W[39]>>25)) & (1<<5))) ) mask &= ~DV_I_51_2_bit; if (mask & DV_I_52_0_bit) mask &= ((((W[38]^W[39])<<11)) | ~DV_I_52_0_bit); if (mask & DV_II_46_2_bit) mask &= ((((W[47]^W[51])<<17)) | ~DV_II_46_2_bit); if (mask & DV_II_48_0_bit) if ( !(!((W[36]^(W[40]>>25)) & (1<<3))) || !((W[35]^(W[40]<<2)) & (1<<30)) ) mask &= ~DV_II_48_0_bit; if (mask & DV_II_49_0_bit) if ( !(!((W[37]^(W[41]>>25)) & (1<<3))) || !((W[36]^(W[41]<<2)) & (1<<30)) ) mask &= ~DV_II_49_0_bit; if (mask & DV_II_49_2_bit) if ( !(!((W[53]^(W[54]<<5)) & (1<<6))) || !(!((W[51]^W[53]) & (1<<6))) || !((W[50]^W[54]) & (1<<1)) || !(!((W[45]^(W[46]<<5)) & (1<<6))) || !(!((W[37]^(W[41]>>25)) & (1<<5))) || !((W[36]^(W[41]>>30)) & (1<<0)) ) mask &= ~DV_II_49_2_bit; if (mask & DV_II_50_0_bit) if ( !((W[55]^W[58]) & (1<<29)) || !(!((W[38]^(W[42]>>25)) & (1<<3))) || !((W[37]^(W[42]<<2)) & (1<<30)) ) mask &= ~DV_II_50_0_bit; if (mask & DV_II_50_2_bit) if ( !(!((W[54]^(W[55]<<5)) & (1<<6))) || !(!((W[52]^W[54]) & (1<<6))) || !((W[51]^W[55]) & (1<<1)) || !((W[45]^W[47]) & (1<<1)) || !(!((W[38]^(W[42]>>25)) & (1<<5))) || !((W[37]^(W[42]>>30)) & (1<<0)) ) mask &= ~DV_II_50_2_bit; if (mask & DV_II_51_0_bit) if ( !(!((W[39]^(W[43]>>25)) & (1<<3))) || !((W[38]^(W[43]<<2)) & (1<<30)) ) mask &= ~DV_II_51_0_bit; if (mask & DV_II_51_2_bit) if ( !(!((W[55]^(W[56]<<5)) & (1<<6))) || !(!((W[53]^W[55]) & (1<<6))) || !((W[52]^W[56]) & (1<<1)) || !((W[46]^W[48]) & (1<<1)) || !(!((W[39]^(W[43]>>25)) & (1<<5))) || !((W[38]^(W[43]>>30)) & (1<<0)) ) mask &= ~DV_II_51_2_bit; if (mask & DV_II_52_0_bit) if ( !(!((W[59]^W[60]) & (1<<29))) || !(!((W[40]^(W[44]>>25)) & (1<<3))) || !(!((W[40]^(W[44]>>25)) & (1<<4))) || !((W[39]^(W[44]<<2)) & (1<<30)) ) mask &= ~DV_II_52_0_bit; if (mask & DV_II_53_0_bit) if ( !((W[58]^W[61]) & (1<<29)) || !(!((W[57]^(W[61]>>25)) & (1<<4))) || !(!((W[41]^(W[45]>>25)) & (1<<3))) || !(!((W[41]^(W[45]>>25)) & (1<<4))) ) mask &= ~DV_II_53_0_bit; if (mask & DV_II_54_0_bit) if ( !(!((W[58]^(W[62]>>25)) & (1<<4))) || !(!((W[42]^(W[46]>>25)) & (1<<3))) || !(!((W[42]^(W[46]>>25)) & (1<<4))) ) mask &= ~DV_II_54_0_bit; if (mask & DV_II_55_0_bit) if ( !(!((W[59]^(W[63]>>25)) & (1<<4))) || !(!((W[57]^(W[59]>>25)) & (1<<4))) || !(!((W[43]^(W[47]>>25)) & (1<<3))) || !(!((W[43]^(W[47]>>25)) & (1<<4))) ) mask &= ~DV_II_55_0_bit; if (mask & DV_II_56_0_bit) if ( !(!((W[60]^(W[64]>>25)) & (1<<4))) || !(!((W[44]^(W[48]>>25)) & (1<<3))) || !(!((W[44]^(W[48]>>25)) & (1<<4))) ) mask &= ~DV_II_56_0_bit; } dvmask[0]=mask; } #ifdef SHA1DC_CUSTOM_TRAILING_INCLUDE_UBC_CHECK_C #include SHA1DC_CUSTOM_TRAILING_INCLUDE_UBC_CHECK_C #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash/sha1
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/hash/sha1/sha1dc/sha1.h
/*** * Copyright 2017 Marc Stevens <[email protected]>, Dan Shumow <[email protected]> * Distributed under the MIT Software License. * See accompanying file LICENSE.txt or copy at * https://opensource.org/licenses/MIT ***/ #ifndef SHA1DC_SHA1_H #define SHA1DC_SHA1_H #if defined(__cplusplus) extern "C" { #endif #ifndef SHA1DC_NO_STANDARD_INCLUDES #include <stdint.h> #endif /* sha-1 compression function that takes an already expanded message, and additionally store intermediate states */ /* only stores states ii (the state between step ii-1 and step ii) when DOSTORESTATEii is defined in ubc_check.h */ void sha1_compression_states(uint32_t[5], const uint32_t[16], uint32_t[80], uint32_t[80][5]); /* // Function type for sha1_recompression_step_T (uint32_t ihvin[5], uint32_t ihvout[5], const uint32_t me2[80], const uint32_t state[5]). // Where 0 <= T < 80 // me2 is an expanded message (the expansion of an original message block XOR'ed with a disturbance vector's message block difference.) // state is the internal state (a,b,c,d,e) before step T of the SHA-1 compression function while processing the original message block. // The function will return: // ihvin: The reconstructed input chaining value. // ihvout: The reconstructed output chaining value. */ typedef void(*sha1_recompression_type)(uint32_t*, uint32_t*, const uint32_t*, const uint32_t*); /* A callback function type that can be set to be called when a collision block has been found: */ /* void collision_block_callback(uint64_t byteoffset, const uint32_t ihvin1[5], const uint32_t ihvin2[5], const uint32_t m1[80], const uint32_t m2[80]) */ typedef void(*collision_block_callback)(uint64_t, const uint32_t*, const uint32_t*, const uint32_t*, const uint32_t*); /* The SHA-1 context. */ typedef struct { uint64_t total; uint32_t ihv[5]; unsigned char buffer[64]; int found_collision; int safe_hash; int detect_coll; int ubc_check; int reduced_round_coll; collision_block_callback callback; uint32_t ihv1[5]; uint32_t ihv2[5]; uint32_t m1[80]; uint32_t m2[80]; uint32_t states[80][5]; } SHA1_CTX; /* Initialize SHA-1 context. */ void SHA1DCInit(SHA1_CTX*); /* Function to enable safe SHA-1 hashing: Collision attacks are thwarted by hashing a detected near-collision block 3 times. Think of it as extending SHA-1 from 80-steps to 240-steps for such blocks: The best collision attacks against SHA-1 have complexity about 2^60, thus for 240-steps an immediate lower-bound for the best cryptanalytic attacks would be 2^180. An attacker would be better off using a generic birthday search of complexity 2^80. Enabling safe SHA-1 hashing will result in the correct SHA-1 hash for messages where no collision attack was detected, but it will result in a different SHA-1 hash for messages where a collision attack was detected. This will automatically invalidate SHA-1 based digital signature forgeries. Enabled by default. */ void SHA1DCSetSafeHash(SHA1_CTX*, int); /* Function to disable or enable the use of Unavoidable Bitconditions (provides a significant speed up). Enabled by default */ void SHA1DCSetUseUBC(SHA1_CTX*, int); /* Function to disable or enable the use of Collision Detection. Enabled by default. */ void SHA1DCSetUseDetectColl(SHA1_CTX*, int); /* function to disable or enable the detection of reduced-round SHA-1 collisions */ /* disabled by default */ void SHA1DCSetDetectReducedRoundCollision(SHA1_CTX*, int); /* function to set a callback function, pass NULL to disable */ /* by default no callback set */ void SHA1DCSetCallback(SHA1_CTX*, collision_block_callback); /* update SHA-1 context with buffer contents */ void SHA1DCUpdate(SHA1_CTX*, const char*, size_t); /* obtain SHA-1 hash from SHA-1 context */ /* returns: 0 = no collision detected, otherwise = collision found => warn user for active attack */ int SHA1DCFinal(unsigned char[20], SHA1_CTX*); #if defined(__cplusplus) } #endif #ifdef SHA1DC_CUSTOM_TRAILING_INCLUDE_SHA1_H #include SHA1DC_CUSTOM_TRAILING_INCLUDE_SHA1_H #endif #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/w32_util.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_win32_w32_util_h__ #define INCLUDE_win32_w32_util_h__ #include "common.h" #include "utf-conv.h" #include "posix.h" #include "path_w32.h" /* #include "common.h" #include "path.h" #include "path_w32.h" #include "utf-conv.h" #include "posix.h" #include "reparse.h" #include "dir.h" */ GIT_INLINE(bool) git_win32__isalpha(wchar_t c) { return ((c >= L'A' && c <= L'Z') || (c >= L'a' && c <= L'z')); } /** * Creates a FindFirstFile(Ex) filter string from a UTF-8 path. * The filter string enumerates all items in the directory. * * @param dest The buffer to receive the filter string. * @param src The UTF-8 path of the directory to enumerate. * @return True if the filter string was created successfully; false otherwise */ bool git_win32__findfirstfile_filter(git_win32_path dest, const char *src); /** * Ensures the given path (file or folder) has the +H (hidden) attribute set * or unset. * * @param path The path that should receive the +H bit. * @param hidden true to set +H, false to unset it * @return 0 on success; -1 on failure */ extern int git_win32__set_hidden(const char *path, bool hidden); /** * Determines if the given file or folder has the hidden attribute set. * @param hidden pointer to store hidden value * @param path The path that should be queried for hiddenness. * @return 0 on success or an error code. */ extern int git_win32__hidden(bool *hidden, const char *path); extern int git_win32__file_attribute_to_stat( struct stat *st, const WIN32_FILE_ATTRIBUTE_DATA *attrdata, const wchar_t *path); /** * Converts a FILETIME structure to a struct timespec. * * @param FILETIME A pointer to a FILETIME * @param ts A pointer to the timespec structure to fill in */ GIT_INLINE(void) git_win32__filetime_to_timespec( const FILETIME *ft, struct timespec *ts) { int64_t winTime = ((int64_t)ft->dwHighDateTime << 32) + ft->dwLowDateTime; winTime -= INT64_C(116444736000000000); /* Windows to Unix Epoch conversion */ ts->tv_sec = (time_t)(winTime / 10000000); #ifdef GIT_USE_NSEC ts->tv_nsec = (winTime % 10000000) * 100; #else ts->tv_nsec = 0; #endif } GIT_INLINE(void) git_win32__timeval_to_filetime( FILETIME *ft, const struct p_timeval tv) { int64_t ticks = (tv.tv_sec * INT64_C(10000000)) + (tv.tv_usec * INT64_C(10)) + INT64_C(116444736000000000); ft->dwHighDateTime = ((ticks >> 32) & INT64_C(0xffffffff)); ft->dwLowDateTime = (ticks & INT64_C(0xffffffff)); } GIT_INLINE(void) git_win32__stat_init( struct stat *st, DWORD dwFileAttributes, DWORD nFileSizeHigh, DWORD nFileSizeLow, FILETIME ftCreationTime, FILETIME ftLastAccessTime, FILETIME ftLastWriteTime) { mode_t mode = S_IREAD; memset(st, 0, sizeof(struct stat)); if (dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) mode |= S_IFDIR; else mode |= S_IFREG; if ((dwFileAttributes & FILE_ATTRIBUTE_READONLY) == 0) mode |= S_IWRITE; st->st_ino = 0; st->st_gid = 0; st->st_uid = 0; st->st_nlink = 1; st->st_mode = mode; st->st_size = ((int64_t)nFileSizeHigh << 32) + nFileSizeLow; st->st_dev = _getdrive() - 1; st->st_rdev = st->st_dev; git_win32__filetime_to_timespec(&ftLastAccessTime, &(st->st_atim)); git_win32__filetime_to_timespec(&ftLastWriteTime, &(st->st_mtim)); git_win32__filetime_to_timespec(&ftCreationTime, &(st->st_ctim)); } GIT_INLINE(void) git_win32__file_information_to_stat( struct stat *st, const BY_HANDLE_FILE_INFORMATION *fileinfo) { git_win32__stat_init(st, fileinfo->dwFileAttributes, fileinfo->nFileSizeHigh, fileinfo->nFileSizeLow, fileinfo->ftCreationTime, fileinfo->ftLastAccessTime, fileinfo->ftLastWriteTime); } #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/error.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_win32_error_h__ #define INCLUDE_win32_error_h__ #include "common.h" extern char *git_win32_get_error_message(DWORD error_code); #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/precompiled.h
#include "common.h" #include <errno.h> #include <limits.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #include <time.h> #include <stdarg.h> #include <sys/types.h> #include <sys/stat.h> #include <io.h> #include <direct.h> #ifdef GIT_THREADS #include "win32/thread.h" #endif #include "git2.h"
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/w32_buffer.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_win32_w32_buffer_h__ #define INCLUDE_win32_w32_buffer_h__ #include "common.h" #include "../buffer.h" /** * Convert a wide character string to UTF-8 and append the results to the * buffer. */ int git_buf_put_w(git_buf *buf, const wchar_t *string_w, size_t len_w); #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/utf-conv.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_win32_utf_conv_h__ #define INCLUDE_win32_utf_conv_h__ #include "common.h" #include <wchar.h> #ifndef WC_ERR_INVALID_CHARS # define WC_ERR_INVALID_CHARS 0x80 #endif /** * Converts a UTF-8 string to wide characters. * * @param dest The buffer to receive the wide string. * @param dest_size The size of the buffer, in characters. * @param src The UTF-8 string to convert. * @return The length of the wide string, in characters (not counting the NULL terminator), or < 0 for failure */ int git__utf8_to_16(wchar_t *dest, size_t dest_size, const char *src); /** * Converts a wide string to UTF-8. * * @param dest The buffer to receive the UTF-8 string. * @param dest_size The size of the buffer, in bytes. * @param src The wide string to convert. * @return The length of the UTF-8 string, in bytes (not counting the NULL terminator), or < 0 for failure */ int git__utf16_to_8(char *dest, size_t dest_size, const wchar_t *src); /** * Converts a UTF-8 string to wide characters. * Memory is allocated to hold the converted string. * The caller is responsible for freeing the string with git__free. * * @param dest Receives a pointer to the wide string. * @param src The UTF-8 string to convert. * @return The length of the wide string, in characters (not counting the NULL terminator), or < 0 for failure */ int git__utf8_to_16_alloc(wchar_t **dest, const char *src); /** * Converts a wide string to UTF-8. * Memory is allocated to hold the converted string. * The caller is responsible for freeing the string with git__free. * * @param dest Receives a pointer to the UTF-8 string. * @param src The wide string to convert. * @return The length of the UTF-8 string, in bytes (not counting the NULL terminator), or < 0 for failure */ int git__utf16_to_8_alloc(char **dest, const wchar_t *src); #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/thread.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_win32_thread_h__ #define INCLUDE_win32_thread_h__ #include "common.h" #if defined (_MSC_VER) # define GIT_RESTRICT __restrict #else # define GIT_RESTRICT __restrict__ #endif typedef struct { HANDLE thread; void *(*proc)(void *); void *param; void *result; } git_thread; typedef CRITICAL_SECTION git_mutex; typedef HANDLE git_cond; typedef struct { void *Ptr; } GIT_SRWLOCK; typedef struct { union { GIT_SRWLOCK srwl; CRITICAL_SECTION csec; } native; } git_rwlock; int git_threads_global_init(void); int git_thread_create(git_thread *GIT_RESTRICT, void *(*) (void *), void *GIT_RESTRICT); int git_thread_join(git_thread *, void **); size_t git_thread_currentid(void); void git_thread_exit(void *); int git_mutex_init(git_mutex *GIT_RESTRICT mutex); int git_mutex_free(git_mutex *); int git_mutex_lock(git_mutex *); int git_mutex_unlock(git_mutex *); int git_cond_init(git_cond *); int git_cond_free(git_cond *); int git_cond_wait(git_cond *, git_mutex *); int git_cond_signal(git_cond *); int git_rwlock_init(git_rwlock *GIT_RESTRICT lock); int git_rwlock_rdlock(git_rwlock *); int git_rwlock_rdunlock(git_rwlock *); int git_rwlock_wrlock(git_rwlock *); int git_rwlock_wrunlock(git_rwlock *); int git_rwlock_free(git_rwlock *); #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/w32_leakcheck.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "w32_leakcheck.h" #if defined(GIT_WIN32_LEAKCHECK) #include "Windows.h" #include "Dbghelp.h" #include "win32/posix.h" #include "hash.h" #include "runtime.h" /* Stack frames (for stack tracing, below) */ static bool g_win32_stack_initialized = false; static HANDLE g_win32_stack_process = INVALID_HANDLE_VALUE; static git_win32_leakcheck_stack_aux_cb_alloc g_aux_cb_alloc = NULL; static git_win32_leakcheck_stack_aux_cb_lookup g_aux_cb_lookup = NULL; int git_win32_leakcheck_stack_set_aux_cb( git_win32_leakcheck_stack_aux_cb_alloc cb_alloc, git_win32_leakcheck_stack_aux_cb_lookup cb_lookup) { g_aux_cb_alloc = cb_alloc; g_aux_cb_lookup = cb_lookup; return 0; } /** * Load symbol table data. This should be done in the primary * thread at startup (under a lock if there are other threads * active). */ void git_win32_leakcheck_stack_init(void) { if (!g_win32_stack_initialized) { g_win32_stack_process = GetCurrentProcess(); SymSetOptions(SYMOPT_LOAD_LINES); SymInitialize(g_win32_stack_process, NULL, TRUE); g_win32_stack_initialized = true; } } /** * Cleanup symbol table data. This should be done in the * primary thead at shutdown (under a lock if there are other * threads active). */ void git_win32_leakcheck_stack_cleanup(void) { if (g_win32_stack_initialized) { SymCleanup(g_win32_stack_process); g_win32_stack_process = INVALID_HANDLE_VALUE; g_win32_stack_initialized = false; } } int git_win32_leakcheck_stack_capture(git_win32_leakcheck_stack_raw_data *pdata, int skip) { if (!g_win32_stack_initialized) { git_error_set(GIT_ERROR_INVALID, "git_win32_stack not initialized."); return GIT_ERROR; } memset(pdata, 0, sizeof(*pdata)); pdata->nr_frames = RtlCaptureStackBackTrace( skip+1, GIT_WIN32_LEAKCHECK_STACK_MAX_FRAMES, pdata->frames, NULL); /* If an "aux" data provider was registered, ask it to capture * whatever data it needs and give us an "aux_id" to it so that * we can refer to it later when reporting. */ if (g_aux_cb_alloc) (g_aux_cb_alloc)(&pdata->aux_id); return 0; } int git_win32_leakcheck_stack_compare( git_win32_leakcheck_stack_raw_data *d1, git_win32_leakcheck_stack_raw_data *d2) { return memcmp(d1, d2, sizeof(*d1)); } int git_win32_leakcheck_stack_format( char *pbuf, size_t buf_len, const git_win32_leakcheck_stack_raw_data *pdata, const char *prefix, const char *suffix) { #define MY_MAX_FILENAME 255 /* SYMBOL_INFO has char FileName[1] at the end. The docs say to * to malloc it with extra space for your desired max filename. */ struct { SYMBOL_INFO symbol; char extra[MY_MAX_FILENAME + 1]; } s; IMAGEHLP_LINE64 line; size_t buf_used = 0; unsigned int k; char detail[MY_MAX_FILENAME * 2]; /* filename plus space for function name and formatting */ size_t detail_len; if (!g_win32_stack_initialized) { git_error_set(GIT_ERROR_INVALID, "git_win32_stack not initialized."); return GIT_ERROR; } if (!prefix) prefix = "\t"; if (!suffix) suffix = "\n"; memset(pbuf, 0, buf_len); memset(&s, 0, sizeof(s)); s.symbol.MaxNameLen = MY_MAX_FILENAME; s.symbol.SizeOfStruct = sizeof(SYMBOL_INFO); memset(&line, 0, sizeof(line)); line.SizeOfStruct = sizeof(IMAGEHLP_LINE64); for (k=0; k < pdata->nr_frames; k++) { DWORD64 frame_k = (DWORD64)pdata->frames[k]; DWORD dwUnused; if (SymFromAddr(g_win32_stack_process, frame_k, 0, &s.symbol) && SymGetLineFromAddr64(g_win32_stack_process, frame_k, &dwUnused, &line)) { const char *pslash; const char *pfile; pslash = strrchr(line.FileName, '\\'); pfile = ((pslash) ? (pslash+1) : line.FileName); p_snprintf(detail, sizeof(detail), "%s%s:%d> %s%s", prefix, pfile, line.LineNumber, s.symbol.Name, suffix); } else { /* This happens when we cross into another module. * For example, in CLAR tests, this is typically * the CRT startup code. Just print an unknown * frame and continue. */ p_snprintf(detail, sizeof(detail), "%s??%s", prefix, suffix); } detail_len = strlen(detail); if (buf_len < (buf_used + detail_len + 1)) { /* we don't have room for this frame in the buffer, so just stop. */ break; } memcpy(&pbuf[buf_used], detail, detail_len); buf_used += detail_len; } /* "aux_id" 0 is reserved to mean no aux data. This is needed to handle * allocs that occur before the aux callbacks were registered. */ if (pdata->aux_id > 0) { p_snprintf(detail, sizeof(detail), "%saux_id: %d%s", prefix, pdata->aux_id, suffix); detail_len = strlen(detail); if ((buf_used + detail_len + 1) < buf_len) { memcpy(&pbuf[buf_used], detail, detail_len); buf_used += detail_len; } /* If an "aux" data provider is still registered, ask it to append its detailed * data to the end of ours using the "aux_id" it gave us when this de-duped * item was created. */ if (g_aux_cb_lookup) (g_aux_cb_lookup)(pdata->aux_id, &pbuf[buf_used], (buf_len - buf_used - 1)); } return GIT_OK; } int git_win32_leakcheck_stack( char * pbuf, size_t buf_len, int skip, const char *prefix, const char *suffix) { git_win32_leakcheck_stack_raw_data data; int error; if ((error = git_win32_leakcheck_stack_capture(&data, skip)) < 0) return error; if ((error = git_win32_leakcheck_stack_format(pbuf, buf_len, &data, prefix, suffix)) < 0) return error; return 0; } /* Strack tracing */ #define STACKTRACE_UID_LEN (15) /** * The stacktrace of an allocation can be distilled * to a unique id based upon the stackframe pointers * and ignoring any size arguments. We will use these * UIDs as the (char const*) __FILE__ argument we * give to the CRT malloc routines. */ typedef struct { char uid[STACKTRACE_UID_LEN + 1]; } git_win32_leakcheck_stacktrace_uid; /** * All mallocs with the same stacktrace will be de-duped * and aggregated into this row. */ typedef struct { git_win32_leakcheck_stacktrace_uid uid; /* must be first */ git_win32_leakcheck_stack_raw_data raw_data; unsigned int count_allocs; /* times this alloc signature seen since init */ unsigned int count_allocs_at_last_checkpoint; /* times since last mark */ unsigned int transient_count_leaks; /* sum of leaks */ } git_win32_leakcheck_stacktrace_row; static CRITICAL_SECTION g_crtdbg_stacktrace_cs; /** * CRTDBG memory leak tracking takes a "char const * const file_name" * and stores the pointer in the heap data (instead of allocing a copy * for itself). Normally, this is not a problem, since we usually pass * in __FILE__. But I'm going to lie to it and pass in the address of * the UID in place of the file_name. Also, I do not want to alloc the * stacktrace data (because we are called from inside our alloc routines). * Therefore, I'm creating a very large static pool array to store row * data. This also eliminates the temptation to realloc it (and move the * UID pointers). * * And to efficiently look for duplicates we need an index on the rows * so we can bsearch it. Again, without mallocing. * * If we observe more than MY_ROW_LIMIT unique malloc signatures, we * fall through and use the traditional __FILE__ processing and don't * try to de-dup them. If your testing hits this limit, just increase * it and try again. */ #define MY_ROW_LIMIT (2 * 1024 * 1024) static git_win32_leakcheck_stacktrace_row g_cs_rows[MY_ROW_LIMIT]; static git_win32_leakcheck_stacktrace_row *g_cs_index[MY_ROW_LIMIT]; static unsigned int g_cs_end = MY_ROW_LIMIT; static unsigned int g_cs_ins = 0; /* insertion point == unique allocs seen */ static unsigned int g_count_total_allocs = 0; /* number of allocs seen */ static unsigned int g_transient_count_total_leaks = 0; /* number of total leaks */ static unsigned int g_transient_count_dedup_leaks = 0; /* number of unique leaks */ static bool g_limit_reached = false; /* had allocs after we filled row table */ static unsigned int g_checkpoint_id = 0; /* to better label leak checkpoints */ static bool g_transient_leaks_since_mark = false; /* payload for hook */ /** * Compare function for bsearch on g_cs_index table. */ static int row_cmp(const void *v1, const void *v2) { git_win32_leakcheck_stack_raw_data *d1 = (git_win32_leakcheck_stack_raw_data*)v1; git_win32_leakcheck_stacktrace_row *r2 = (git_win32_leakcheck_stacktrace_row *)v2; return (git_win32_leakcheck_stack_compare(d1, &r2->raw_data)); } /** * Unique insert the new data into the row and index tables. * We have to sort by the stackframe data itself, not the uid. */ static git_win32_leakcheck_stacktrace_row * insert_unique( const git_win32_leakcheck_stack_raw_data *pdata) { size_t pos; if (git__bsearch(g_cs_index, g_cs_ins, pdata, row_cmp, &pos) < 0) { /* Append new unique item to row table. */ memcpy(&g_cs_rows[g_cs_ins].raw_data, pdata, sizeof(*pdata)); sprintf(g_cs_rows[g_cs_ins].uid.uid, "##%08lx", g_cs_ins); /* Insert pointer to it into the proper place in the index table. */ if (pos < g_cs_ins) memmove(&g_cs_index[pos+1], &g_cs_index[pos], (g_cs_ins - pos)*sizeof(g_cs_index[0])); g_cs_index[pos] = &g_cs_rows[g_cs_ins]; g_cs_ins++; } g_cs_index[pos]->count_allocs++; return g_cs_index[pos]; } /** * Hook function to receive leak data from the CRT. (This includes * both "<file_name>:(<line_number>)" data, but also each of the * various headers and fields. * * Scan this for the special "##<pos>" UID forms that we substituted * for the "<file_name>". Map <pos> back to the row data and * increment its leak count. * * See https://msdn.microsoft.com/en-us/library/74kabxyx.aspx * * We suppress the actual crtdbg output. */ static int __cdecl report_hook(int nRptType, char *szMsg, int *retVal) { static int hook_result = TRUE; /* FALSE to get stock dump; TRUE to suppress. */ unsigned int pos; *retVal = 0; /* do not invoke debugger */ if ((szMsg[0] != '#') || (szMsg[1] != '#')) return hook_result; if (sscanf(&szMsg[2], "%08lx", &pos) < 1) return hook_result; if (pos >= g_cs_ins) return hook_result; if (g_transient_leaks_since_mark) { if (g_cs_rows[pos].count_allocs == g_cs_rows[pos].count_allocs_at_last_checkpoint) return hook_result; } g_cs_rows[pos].transient_count_leaks++; if (g_cs_rows[pos].transient_count_leaks == 1) g_transient_count_dedup_leaks++; g_transient_count_total_leaks++; return hook_result; } /** * Write leak data to all of the various places we need. * We force the caller to sprintf() the message first * because we want to avoid fprintf() because it allocs. */ static void my_output(const char *buf) { fwrite(buf, strlen(buf), 1, stderr); OutputDebugString(buf); } /** * For each row with leaks, dump a stacktrace for it. */ static void dump_summary(const char *label) { unsigned int k; char buf[10 * 1024]; if (g_transient_count_total_leaks == 0) return; fflush(stdout); fflush(stderr); my_output("\n"); if (g_limit_reached) { sprintf(buf, "LEAK SUMMARY: de-dup row table[%d] filled. Increase MY_ROW_LIMIT.\n", MY_ROW_LIMIT); my_output(buf); } if (!label) label = ""; if (g_transient_leaks_since_mark) { sprintf(buf, "LEAK CHECKPOINT %d: leaks %d unique %d: %s\n", g_checkpoint_id, g_transient_count_total_leaks, g_transient_count_dedup_leaks, label); my_output(buf); } else { sprintf(buf, "LEAK SUMMARY: TOTAL leaks %d de-duped %d: %s\n", g_transient_count_total_leaks, g_transient_count_dedup_leaks, label); my_output(buf); } my_output("\n"); for (k = 0; k < g_cs_ins; k++) { if (g_cs_rows[k].transient_count_leaks > 0) { sprintf(buf, "LEAK: %s leaked %d of %d times:\n", g_cs_rows[k].uid.uid, g_cs_rows[k].transient_count_leaks, g_cs_rows[k].count_allocs); my_output(buf); if (git_win32_leakcheck_stack_format( buf, sizeof(buf), &g_cs_rows[k].raw_data, NULL, NULL) >= 0) { my_output(buf); } my_output("\n"); } } fflush(stderr); } /** * Initialize our memory leak tracking and de-dup data structures. * This should ONLY be called by git_libgit2_init(). */ void git_win32_leakcheck_stacktrace_init(void) { InitializeCriticalSection(&g_crtdbg_stacktrace_cs); EnterCriticalSection(&g_crtdbg_stacktrace_cs); _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); LeaveCriticalSection(&g_crtdbg_stacktrace_cs); } int git_win32_leakcheck_stacktrace_dump( git_win32_leakcheck_stacktrace_options opt, const char *label) { _CRT_REPORT_HOOK old; unsigned int k; int r = 0; #define IS_BIT_SET(o,b) (((o) & (b)) != 0) bool b_set_mark = IS_BIT_SET(opt, GIT_WIN32_LEAKCHECK_STACKTRACE_SET_MARK); bool b_leaks_since_mark = IS_BIT_SET(opt, GIT_WIN32_LEAKCHECK_STACKTRACE_LEAKS_SINCE_MARK); bool b_leaks_total = IS_BIT_SET(opt, GIT_WIN32_LEAKCHECK_STACKTRACE_LEAKS_TOTAL); bool b_quiet = IS_BIT_SET(opt, GIT_WIN32_LEAKCHECK_STACKTRACE_QUIET); if (b_leaks_since_mark && b_leaks_total) { git_error_set(GIT_ERROR_INVALID, "cannot combine LEAKS_SINCE_MARK and LEAKS_TOTAL."); return GIT_ERROR; } if (!b_set_mark && !b_leaks_since_mark && !b_leaks_total) { git_error_set(GIT_ERROR_INVALID, "nothing to do."); return GIT_ERROR; } EnterCriticalSection(&g_crtdbg_stacktrace_cs); if (b_leaks_since_mark || b_leaks_total) { /* All variables with "transient" in the name are per-dump counters * and reset before each dump. This lets us handle checkpoints. */ g_transient_count_total_leaks = 0; g_transient_count_dedup_leaks = 0; for (k = 0; k < g_cs_ins; k++) { g_cs_rows[k].transient_count_leaks = 0; } } g_transient_leaks_since_mark = b_leaks_since_mark; old = _CrtSetReportHook(report_hook); _CrtDumpMemoryLeaks(); _CrtSetReportHook(old); if (b_leaks_since_mark || b_leaks_total) { r = g_transient_count_dedup_leaks; if (!b_quiet) dump_summary(label); } if (b_set_mark) { for (k = 0; k < g_cs_ins; k++) { g_cs_rows[k].count_allocs_at_last_checkpoint = g_cs_rows[k].count_allocs; } g_checkpoint_id++; } LeaveCriticalSection(&g_crtdbg_stacktrace_cs); return r; } /** * Shutdown our memory leak tracking and dump summary data. * This should ONLY be called by git_libgit2_shutdown(). * * We explicitly call _CrtDumpMemoryLeaks() during here so * that we can compute summary data for the leaks. We print * the stacktrace of each unique leak. * * This cleanup does not happen if the app calls exit() * without calling the libgit2 shutdown code. * * This info we print here is independent of any automatic * reporting during exit() caused by _CRTDBG_LEAK_CHECK_DF. * Set it in your app if you also want traditional reporting. */ void git_win32_leakcheck_stacktrace_cleanup(void) { /* At shutdown/cleanup, dump cumulative leak info * with everything since startup. This might generate * extra noise if the caller has been doing checkpoint * dumps, but it might also eliminate some false * positives for resources previously reported during * checkpoints. */ git_win32_leakcheck_stacktrace_dump( GIT_WIN32_LEAKCHECK_STACKTRACE_LEAKS_TOTAL, "CLEANUP"); DeleteCriticalSection(&g_crtdbg_stacktrace_cs); } const char *git_win32_leakcheck_stacktrace(int skip, const char *file) { git_win32_leakcheck_stack_raw_data new_data; git_win32_leakcheck_stacktrace_row *row; const char * result = file; if (git_win32_leakcheck_stack_capture(&new_data, skip+1) < 0) return result; EnterCriticalSection(&g_crtdbg_stacktrace_cs); if (g_cs_ins < g_cs_end) { row = insert_unique(&new_data); result = row->uid.uid; } else { g_limit_reached = true; } g_count_total_allocs++; LeaveCriticalSection(&g_crtdbg_stacktrace_cs); return result; } static void git_win32_leakcheck_global_shutdown(void) { git_win32_leakcheck_stacktrace_cleanup(); git_win32_leakcheck_stack_cleanup(); } bool git_win32_leakcheck_has_leaks(void) { return (g_transient_count_total_leaks > 0); } int git_win32_leakcheck_global_init(void) { git_win32_leakcheck_stacktrace_init(); git_win32_leakcheck_stack_init(); return git_runtime_shutdown_register(git_win32_leakcheck_global_shutdown); } #else int git_win32_leakcheck_global_init(void) { return 0; } #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/error.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "error.h" #include "utf-conv.h" #ifdef GIT_WINHTTP # include <winhttp.h> #endif char *git_win32_get_error_message(DWORD error_code) { LPWSTR lpMsgBuf = NULL; HMODULE hModule = NULL; char *utf8_msg = NULL; DWORD dwFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS; if (!error_code) return NULL; #ifdef GIT_WINHTTP /* Errors raised by WinHTTP are not in the system resource table */ if (error_code >= WINHTTP_ERROR_BASE && error_code <= WINHTTP_ERROR_LAST) hModule = GetModuleHandleW(L"winhttp"); #endif GIT_UNUSED(hModule); if (hModule) dwFlags |= FORMAT_MESSAGE_FROM_HMODULE; else dwFlags |= FORMAT_MESSAGE_FROM_SYSTEM; if (FormatMessageW(dwFlags, hModule, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&lpMsgBuf, 0, NULL)) { /* Convert the message to UTF-8. If this fails, we will * return NULL, which is a condition expected by the caller */ if (git__utf16_to_8_alloc(&utf8_msg, lpMsgBuf) < 0) utf8_msg = NULL; LocalFree(lpMsgBuf); } return utf8_msg; }
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/findfile.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_win32_findfile_h__ #define INCLUDE_win32_findfile_h__ #include "common.h" extern int git_win32__find_system_dirs(git_buf *out, const wchar_t *subpath); extern int git_win32__find_global_dirs(git_buf *out); extern int git_win32__find_xdg_dirs(git_buf *out); extern int git_win32__find_programdata_dirs(git_buf *out); #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/win32-compat.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_win32_win32_compat_h__ #define INCLUDE_win32_win32_compat_h__ #include <stdint.h> #include <time.h> #include <wchar.h> #include <sys/stat.h> #include <sys/types.h> typedef long suseconds_t; struct p_timeval { time_t tv_sec; suseconds_t tv_usec; }; struct p_timespec { time_t tv_sec; long tv_nsec; }; #define timespec p_timespec struct p_stat { _dev_t st_dev; _ino_t st_ino; mode_t st_mode; short st_nlink; short st_uid; short st_gid; _dev_t st_rdev; __int64 st_size; struct timespec st_atim; struct timespec st_mtim; struct timespec st_ctim; #define st_atime st_atim.tv_sec #define st_mtime st_mtim.tv_sec #define st_ctime st_ctim.tv_sec #define st_atime_nsec st_atim.tv_nsec #define st_mtime_nsec st_mtim.tv_nsec #define st_ctime_nsec st_ctim.tv_nsec }; #define stat p_stat #endif
0
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src
repos/gyro/.gyro/zig-libgit2-mattnite-github.com-0537beea/pkg/libgit2/src/win32/path_w32.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_win32_path_w32_h__ #define INCLUDE_win32_path_w32_h__ #include "common.h" /** * Create a Win32 path (in UCS-2 format) from a UTF-8 string. If the given * path is relative, then it will be turned into an absolute path by having * the current working directory prepended. * * @param dest The buffer to receive the wide string. * @param src The UTF-8 string to convert. * @return The length of the wide string, in characters (not counting the NULL terminator), or < 0 for failure */ extern int git_win32_path_from_utf8(git_win32_path dest, const char *src); /** * Create a Win32 path (in UCS-2 format) from a UTF-8 string. If the given * path is relative, then it will not be turned into an absolute path. * * @param dest The buffer to receive the wide string. * @param src The UTF-8 string to convert. * @return The length of the wide string, in characters (not counting the NULL terminator), or < 0 for failure */ extern int git_win32_path_relative_from_utf8(git_win32_path dest, const char *src); /** * Canonicalize a Win32 UCS-2 path so that it is suitable for delivery to the * Win32 APIs: remove multiple directory separators, squashing to a single one, * strip trailing directory separators, ensure directory separators are all * canonical (always backslashes, never forward slashes) and process any * directory entries of '.' or '..'. * * Note that this is intended to be used on absolute Windows paths, those * that start with `C:\`, `\\server\share`, `\\?\`, etc. * * This processes the buffer in place. * * @param path The buffer to process * @return The new length of the buffer, in wchar_t's (not counting the NULL terminator) */ extern int git_win32_path_canonicalize(git_win32_path path); /** * Create an internal format (posix-style) UTF-8 path from a Win32 UCS-2 path. * * @param dest The buffer to receive the UTF-8 string. * @param src The wide string to convert. * @return The length of the UTF-8 string, in bytes (not counting the NULL terminator), or < 0 for failure */ extern int git_win32_path_to_utf8(git_win32_utf8_path dest, const wchar_t *src); /** * Get the short name for the terminal path component in the given path. * For example, given "C:\Foo\Bar\Asdf.txt", this will return the short name * for the file "Asdf.txt". * * @param path The given path in UTF-8 * @return The name of the shortname for the given path */ extern char *git_win32_path_8dot3_name(const char *path); extern int git_win32_path_readlink_w(git_win32_path dest, const git_win32_path path); /** * Removes any trailing backslashes from a path, except in the case of a drive * letter path (C:\, D:\, etc.). This function cannot fail. * * @param path The path which should be trimmed. * @return The length of the modified string (<= the input length) */ size_t git_win32_path_trim_end(wchar_t *str, size_t len); /** * Removes any of the following namespace prefixes from a path, * if found: "\??\", "\\?\", "\\?\UNC\". This function cannot fail. * * @param path The path which should be converted. * @return The length of the modified string (<= the input length) */ size_t git_win32_path_remove_namespace(wchar_t *str, size_t len); #endif