repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
pavankumarbn/VTKExamples
|
src/Cxx/Developers/vtkTestAlgorithmSource.h
|
#ifndef __vtkTestAlgorithmSource_h
#define __vtkTestAlgorithmSource_h
#include <vtkAlgorithm.h>
class vtkDataSet;
class vtkTest1;
class vtkTestAlgorithmSource : public vtkAlgorithm
{
public:
static vtkTestAlgorithmSource *New();
vtkTypeMacro(vtkTestAlgorithmSource,vtkAlgorithm);
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// Get the output data object for a port on this algorithm.
vtkTest1* GetOutput();
vtkTest1* GetOutput(int);
virtual void SetOutput(vtkDataObject* d);
// Description:
// see vtkAlgorithm for details
virtual int ProcessRequest(vtkInformation*,
vtkInformationVector**,
vtkInformationVector*);
protected:
vtkTestAlgorithmSource();
~vtkTestAlgorithmSource();
// Description:
// This is called by the superclass.
// This is the method you should override.
virtual int RequestDataObject(
vtkInformation* request,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector );
// convenience method
virtual int RequestInformation(
vtkInformation* request,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector );
// Description:
// This is called by the superclass.
// This is the method you should override.
virtual int RequestData(
vtkInformation* request,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector );
// Description:
// This is called by the superclass.
// This is the method you should override.
virtual int RequestUpdateExtent(
vtkInformation*,
vtkInformationVector**,
vtkInformationVector* );
virtual int FillOutputPortInformation( int port, vtkInformation* info );
private:
vtkTestAlgorithmSource( const vtkTestAlgorithmSource& ); // Not implemented.
void operator = ( const vtkTestAlgorithmSource& ); // Not implemented.
};
#endif
|
pavankumarbn/VTKExamples
|
src/Cxx/Developers/vtkTestAlgorithmFilter.h
|
#ifndef __vtkTestAlgorithmFilter_h
#define __vtkTestAlgorithmFilter_h
#include <vtkAlgorithm.h>
class vtkDataSet;
class vtkTest;
class vtkTestAlgorithmFilter : public vtkAlgorithm
{
public:
static vtkTestAlgorithmFilter *New();
vtkTypeMacro(vtkTestAlgorithmFilter,vtkAlgorithm);
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// Get the output data object for a port on this algorithm.
vtkTest* GetOutput();
vtkTest* GetOutput(int);
virtual void SetOutput(vtkDataObject* d);
// Description:
// see vtkAlgorithm for details
virtual int ProcessRequest(vtkInformation*,
vtkInformationVector**,
vtkInformationVector*);
// this method is not recommended for use, but lots of old style filters use it
vtkDataObject* GetInput();
vtkDataObject* GetInput(int port);
vtkTest* GetLabelHierarchyInput(int port);
// Description:
// Set an input of this algorithm. You should not override these
// methods because they are not the only way to connect a pipeline.
// Note that these methods support old-style pipeline connections.
// When writing new code you should use the more general
// vtkAlgorithm::SetInputConnection(). These methods transform the
// input index to the input port index, not an index of a connection
// within a single port.
void SetInput( vtkDataObject* );
void SetInput( int, vtkDataObject* );
// Description:
// Add an input of this algorithm. Note that these methods support
// old-style pipeline connections. When writing new code you should
// use the more general vtkAlgorithm::AddInputConnection(). See
// SetInput() for details.
void AddInput( vtkDataObject* );
void AddInput( int, vtkDataObject* );
protected:
vtkTestAlgorithmFilter();
~vtkTestAlgorithmFilter();
// Description:
// This is called by the superclass.
// This is the method you should override.
virtual int RequestDataObject(
vtkInformation* request,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector );
// convenience method
virtual int RequestInformation(
vtkInformation* request,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector );
// Description:
// This is called by the superclass.
// This is the method you should override.
virtual int RequestData(
vtkInformation* request,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector );
// Description:
// This is called by the superclass.
// This is the method you should override.
virtual int RequestUpdateExtent(
vtkInformation*,
vtkInformationVector**,
vtkInformationVector* );
virtual int FillOutputPortInformation( int port, vtkInformation* info );
virtual int FillInputPortInformation( int port, vtkInformation* info );
private:
vtkTestAlgorithmFilter( const vtkTestAlgorithmFilter& ); // Not implemented.
void operator = ( const vtkTestAlgorithmFilter& ); // Not implemented.
};
#endif
|
pavankumarbn/VTKExamples
|
src/Cxx/Interaction/vtkTestFilter.h
|
#ifndef __vtkTestFilter_h
#define __vtkTestFilter_h
#include <vtkPolyDataAlgorithm.h>
class vtkTestFilter : public vtkPolyDataAlgorithm
{
public:
vtkTypeMacro(vtkTestFilter,vtkPolyDataAlgorithm);
static vtkTestFilter *New();
int RefreshEvent;
protected:
vtkTestFilter();
int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
private:
vtkTestFilter(const vtkTestFilter&); // Not implemented.
void operator=(const vtkTestFilter&); // Not implemented.
};
#endif
#include <vtkObjectFactory.h>
#include <vtkCommand.h>
#include <vtkStreamingDemandDrivenPipeline.h>
#include <vtkInformationVector.h>
#include <vtkInformation.h>
#include <vtkDataObject.h>
#include <vtkSmartPointer.h>
#include <vtkAppendPolyData.h>
#include <vtkSphereSource.h>
vtkStandardNewMacro(vtkTestFilter);
vtkTestFilter::vtkTestFilter()
{
this->SetNumberOfInputPorts(0);
this->RefreshEvent = vtkCommand::UserEvent + 1;
}
int vtkTestFilter::RequestData(vtkInformation *vtkNotUsed(request),
vtkInformationVector **,
vtkInformationVector *)
{
// Get the info object
// vtkInformation *outInfo = outputVector->GetInformationObject(0);
// vtkPolyData *output = vtkPolyData::SafeDownCast(
// outInfo->Get(vtkDataObject::DATA_OBJECT()));
this->InvokeEvent(this->RefreshEvent, nullptr);
return 1;
}
|
ThomasAdam/gameoftrees
|
lib/diff_output.c
|
<reponame>ThomasAdam/gameoftrees
/* Common parts for printing diff output */
/*
* Copyright (c) 2020 <NAME> <<EMAIL>>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <ctype.h>
#include <errno.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arraylist.h>
#include <diff_main.h>
#include <diff_output.h>
#include "diff_internal.h"
static int
get_atom_byte(int *ch, struct diff_atom *atom, off_t off)
{
off_t cur;
if (atom->at != NULL) {
*ch = atom->at[off];
return 0;
}
cur = ftello(atom->root->f);
if (cur == -1)
return errno;
if (cur != atom->pos + off &&
fseeko(atom->root->f, atom->pos + off, SEEK_SET) == -1)
return errno;
*ch = fgetc(atom->root->f);
if (*ch == EOF && ferror(atom->root->f))
return errno;
return 0;
}
int
diff_output_lines(struct diff_output_info *outinfo, FILE *dest,
const char *prefix, struct diff_atom *start_atom,
unsigned int count)
{
struct diff_atom *atom;
off_t outoff = 0, *offp;
int rc;
if (outinfo && outinfo->line_offsets.len > 0) {
unsigned int idx = outinfo->line_offsets.len - 1;
outoff = outinfo->line_offsets.head[idx];
}
foreach_diff_atom(atom, start_atom, count) {
off_t outlen = 0;
int i, ch;
unsigned int len = atom->len;
rc = fprintf(dest, "%s", prefix);
if (rc < 0)
return errno;
outlen += rc;
if (len) {
rc = get_atom_byte(&ch, atom, len - 1);
if (rc)
return rc;
if (ch == '\n')
len--;
if (len) {
rc = get_atom_byte(&ch, atom, len - 1);
if (rc)
return rc;
if (ch == '\r')
len--;
}
}
for (i = 0; i < len; i++) {
rc = get_atom_byte(&ch, atom, i);
if (rc)
return rc;
rc = fprintf(dest, "%c", (unsigned char)ch);
if (rc < 0)
return errno;
outlen += rc;
}
rc = fprintf(dest, "\n");
if (rc < 0)
return errno;
outlen += rc;
if (outinfo) {
ARRAYLIST_ADD(offp, outinfo->line_offsets);
if (offp == NULL)
return ENOMEM;
outoff += outlen;
*offp = outoff;
}
}
return DIFF_RC_OK;
}
int
diff_output_chunk_left_version(struct diff_output_info **output_info,
FILE *dest,
const struct diff_input_info *info,
const struct diff_result *result,
const struct diff_chunk_context *cc)
{
int rc, c_idx;
struct diff_output_info *outinfo = NULL;
if (diff_range_empty(&cc->left))
return DIFF_RC_OK;
if (output_info) {
*output_info = diff_output_info_alloc();
if (*output_info == NULL)
return ENOMEM;
outinfo = *output_info;
}
/* Write out all chunks on the left side. */
for (c_idx = cc->chunk.start; c_idx < cc->chunk.end; c_idx++) {
const struct diff_chunk *c = &result->chunks.head[c_idx];
if (c->left_count) {
rc = diff_output_lines(outinfo, dest, "",
c->left_start, c->left_count);
if (rc)
return rc;
}
}
return DIFF_RC_OK;
}
int
diff_output_chunk_right_version(struct diff_output_info **output_info,
FILE *dest,
const struct diff_input_info *info,
const struct diff_result *result,
const struct diff_chunk_context *cc)
{
int rc, c_idx;
struct diff_output_info *outinfo = NULL;
if (diff_range_empty(&cc->right))
return DIFF_RC_OK;
if (output_info) {
*output_info = diff_output_info_alloc();
if (*output_info == NULL)
return ENOMEM;
outinfo = *output_info;
}
/* Write out all chunks on the right side. */
for (c_idx = cc->chunk.start; c_idx < cc->chunk.end; c_idx++) {
const struct diff_chunk *c = &result->chunks.head[c_idx];
if (c->right_count) {
rc = diff_output_lines(outinfo, dest, "", c->right_start,
c->right_count);
if (rc)
return rc;
}
}
return DIFF_RC_OK;
}
int
diff_output_trailing_newline_msg(struct diff_output_info *outinfo, FILE *dest,
const struct diff_chunk *c)
{
enum diff_chunk_type chunk_type = diff_chunk_type(c);
struct diff_atom *atom, *start_atom;
unsigned int atom_count;
int rc, ch;
off_t outoff = 0, *offp;
if (chunk_type == CHUNK_MINUS || chunk_type == CHUNK_SAME) {
start_atom = c->left_start;
atom_count = c->left_count;
} else if (chunk_type == CHUNK_PLUS) {
start_atom = c->right_start;
atom_count = c->right_count;
} else
return EINVAL;
/* Locate the last atom. */
if (atom_count == 0)
return EINVAL;
atom = &start_atom[atom_count - 1];
rc = get_atom_byte(&ch, atom, atom->len - 1);
if (rc != DIFF_RC_OK)
return rc;
if (ch != '\n') {
if (outinfo && outinfo->line_offsets.len > 0) {
unsigned int idx = outinfo->line_offsets.len - 1;
outoff = outinfo->line_offsets.head[idx];
}
rc = fprintf(dest, "\\ No newline at end of file\n");
if (rc < 0)
return errno;
if (outinfo) {
ARRAYLIST_ADD(offp, outinfo->line_offsets);
if (offp == NULL)
return ENOMEM;
outoff += rc;
*offp = outoff;
}
}
return DIFF_RC_OK;
}
static bool
is_function_prototype(unsigned char ch)
{
return (isalpha(ch) || ch == '_' || ch == '$');
}
#define begins_with(s, pre) (strncmp(s, pre, sizeof(pre)-1) == 0)
int
diff_output_match_function_prototype(char *prototype, size_t prototype_size,
int *last_prototype_idx, const struct diff_result *result,
const struct diff_chunk_context *cc)
{
struct diff_atom *start_atom, *atom;
const struct diff_data *data;
unsigned char buf[DIFF_FUNCTION_CONTEXT_SIZE];
char *state = NULL;
int rc, i, ch;
if (result->left->atoms.len > 0 && cc->left.start > 0) {
data = result->left;
start_atom = &data->atoms.head[cc->left.start - 1];
} else
return DIFF_RC_OK;
diff_data_foreach_atom_backwards_from(start_atom, atom, data) {
int atom_idx = diff_atom_root_idx(data, atom);
if (atom_idx < *last_prototype_idx)
break;
rc = get_atom_byte(&ch, atom, 0);
if (rc)
return rc;
buf[0] = (unsigned char)ch;
if (!is_function_prototype(buf[0]))
continue;
for (i = 1; i < atom->len && i < sizeof(buf) - 1; i++) {
rc = get_atom_byte(&ch, atom, i);
if (rc)
return rc;
if (ch == '\n')
break;
buf[i] = (unsigned char)ch;
}
buf[i] = '\0';
if (begins_with(buf, "private:")) {
if (!state)
state = " (private)";
} else if (begins_with(buf, "protected:")) {
if (!state)
state = " (protected)";
} else if (begins_with(buf, "public:")) {
if (!state)
state = " (public)";
} else {
if (state) /* don't care about truncation */
strlcat(buf, state, sizeof(buf));
strlcpy(prototype, buf, prototype_size);
break;
}
}
*last_prototype_idx = diff_atom_root_idx(data, start_atom);
return DIFF_RC_OK;
}
struct diff_output_info *
diff_output_info_alloc(void)
{
struct diff_output_info *output_info;
off_t *offp;
output_info = malloc(sizeof(*output_info));
if (output_info != NULL) {
ARRAYLIST_INIT(output_info->line_offsets, 128);
ARRAYLIST_ADD(offp, output_info->line_offsets);
if (offp == NULL) {
diff_output_info_free(output_info);
return NULL;
}
*offp = 0;
}
return output_info;
}
void
diff_output_info_free(struct diff_output_info *output_info)
{
ARRAYLIST_FREE(output_info->line_offsets);
free(output_info);
}
const char *
diff_output_get_label_left(const struct diff_input_info *info)
{
if (info->flags & DIFF_INPUT_LEFT_NONEXISTENT)
return "/dev/null";
return info->left_path ? : "a";
}
const char *
diff_output_get_label_right(const struct diff_input_info *info)
{
if (info->flags & DIFF_INPUT_RIGHT_NONEXISTENT)
return "/dev/null";
return info->right_path ? : "b";
}
|
ThomasAdam/gameoftrees
|
lib/diff_output_edscript.c
|
<reponame>ThomasAdam/gameoftrees
/* Produce ed(1) script output from a diff_result. */
/*
* Copyright (c) 2020 <NAME> <<EMAIL>>
* Copyright (c) 2020 <NAME> <<EMAIL>>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <arraylist.h>
#include <diff_main.h>
#include <diff_output.h>
#include "diff_internal.h"
static int
output_edscript_chunk(struct diff_output_info *outinfo,
FILE *dest, const struct diff_input_info *info,
const struct diff_result *result,
struct diff_chunk_context *cc)
{
off_t outoff = 0, *offp;
int left_start, left_len, right_start, right_len;
int rc;
left_len = cc->left.end - cc->left.start;
if (left_len < 0)
return EINVAL;
else if (result->left->atoms.len == 0)
left_start = 0;
else if (left_len == 0 && cc->left.start > 0)
left_start = cc->left.start;
else
left_start = cc->left.start + 1;
right_len = cc->right.end - cc->right.start;
if (right_len < 0)
return EINVAL;
else if (result->right->atoms.len == 0)
right_start = 0;
else if (right_len == 0 && cc->right.start > 0)
right_start = cc->right.start;
else
right_start = cc->right.start + 1;
if (left_len == 0) {
/* addition */
if (right_len == 1) {
rc = fprintf(dest, "%da%d\n", left_start, right_start);
} else {
rc = fprintf(dest, "%da%d,%d\n", left_start,
right_start, cc->right.end);
}
} else if (right_len == 0) {
/* deletion */
if (left_len == 1) {
rc = fprintf(dest, "%dd%d\n", left_start,
right_start);
} else {
rc = fprintf(dest, "%d,%dd%d\n", left_start,
cc->left.end, right_start);
}
} else {
/* change */
if (left_len == 1 && right_len == 1) {
rc = fprintf(dest, "%dc%d\n", left_start, right_start);
} else if (left_len == 1) {
rc = fprintf(dest, "%dc%d,%d\n", left_start,
right_start, cc->right.end);
} else if (right_len == 1) {
rc = fprintf(dest, "%d,%dc%d\n", left_start,
cc->left.end, right_start);
} else {
rc = fprintf(dest, "%d,%dc%d,%d\n", left_start,
cc->left.end, right_start, cc->right.end);
}
}
if (rc < 0)
return errno;
if (outinfo) {
ARRAYLIST_ADD(offp, outinfo->line_offsets);
if (offp == NULL)
return ENOMEM;
outoff += rc;
*offp = outoff;
}
return DIFF_RC_OK;
}
int
diff_output_edscript(struct diff_output_info **output_info,
FILE *dest, const struct diff_input_info *info,
const struct diff_result *result)
{
struct diff_output_info *outinfo = NULL;
struct diff_chunk_context cc = {};
int atomizer_flags = (result->left->atomizer_flags|
result->right->atomizer_flags);
int flags = (result->left->root->diff_flags |
result->right->root->diff_flags);
bool force_text = (flags & DIFF_FLAG_FORCE_TEXT_DATA);
bool have_binary = (atomizer_flags & DIFF_ATOMIZER_FOUND_BINARY_DATA);
int i, rc;
if (!result)
return EINVAL;
if (result->rc != DIFF_RC_OK)
return result->rc;
if (output_info) {
*output_info = diff_output_info_alloc();
if (*output_info == NULL)
return ENOMEM;
outinfo = *output_info;
}
if (have_binary && !force_text) {
for (i = 0; i < result->chunks.len; i++) {
struct diff_chunk *c = &result->chunks.head[i];
enum diff_chunk_type t = diff_chunk_type(c);
if (t != CHUNK_MINUS && t != CHUNK_PLUS)
continue;
fprintf(dest, "Binary files %s and %s differ\n",
diff_output_get_label_left(info),
diff_output_get_label_right(info));
break;
}
return DIFF_RC_OK;
}
for (i = 0; i < result->chunks.len; i++) {
struct diff_chunk *chunk = &result->chunks.head[i];
enum diff_chunk_type t = diff_chunk_type(chunk);
struct diff_chunk_context next;
if (t != CHUNK_MINUS && t != CHUNK_PLUS)
continue;
if (diff_chunk_context_empty(&cc)) {
/* Note down the start point, any number of subsequent
* chunks may be joined up to this chunk by being
* directly adjacent. */
diff_chunk_context_get(&cc, result, i, 0);
continue;
}
/* There already is a previous chunk noted down for being
* printed. Does it join up with this one? */
diff_chunk_context_get(&next, result, i, 0);
if (diff_chunk_contexts_touch(&cc, &next)) {
/* This next context touches or overlaps the previous
* one, join. */
diff_chunk_contexts_merge(&cc, &next);
continue;
}
rc = output_edscript_chunk(outinfo, dest, info, result, &cc);
if (rc != DIFF_RC_OK)
return rc;
cc = next;
}
if (!diff_chunk_context_empty(&cc))
return output_edscript_chunk(outinfo, dest, info, result, &cc);
return DIFF_RC_OK;
}
|
ThomasAdam/gameoftrees
|
lib/error.c
|
<filename>lib/error.c
/*
* Copyright (c) 2018 <NAME> <<EMAIL>>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <errno.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sha1.h>
#include <zlib.h>
#include <uuid.h>
#include "got_compat.h"
#include "got_error.h"
#include "got_object.h"
#include "got_lib_delta.h"
#include "got_lib_inflate.h"
#include "got_lib_object.h"
#include "got_lib_sha1.h"
#ifndef nitems
#define nitems(_a) (sizeof(_a) / sizeof((_a)[0]))
#endif
static struct got_custom_error {
struct got_error err;
char msg[4080];
} custom_errors[16];
static struct got_custom_error *
get_custom_err(void)
{
static unsigned int idx;
return &custom_errors[(idx++) % nitems(custom_errors)];
}
const struct got_error *
got_error(int code)
{
size_t i;
for (i = 0; i < nitems(got_errors); i++) {
if (code == got_errors[i].code)
return &got_errors[i];
}
abort();
}
const struct got_error *
got_error_msg(int code, const char *msg)
{
struct got_custom_error *cerr = get_custom_err();
struct got_error *err = &cerr->err;
size_t i;
for (i = 0; i < nitems(got_errors); i++) {
if (code == got_errors[i].code) {
err->code = code;
strlcpy(cerr->msg, msg, sizeof(cerr->msg));
err->msg = cerr->msg;
return err;
}
}
abort();
}
const struct got_error *
got_error_from_errno(const char *prefix)
{
struct got_custom_error *cerr = get_custom_err();
struct got_error *err = &cerr->err;
char strerr[128];
strerror_r(errno, strerr, sizeof(strerr));
snprintf(cerr->msg, sizeof(cerr->msg), "%s: %s", prefix, strerr);
err->code = GOT_ERR_ERRNO;
err->msg = cerr->msg;
return err;
}
const struct got_error *
got_error_from_errno2(const char *prefix, const char *prefix2)
{
struct got_custom_error *cerr = get_custom_err();
struct got_error *err = &cerr->err;
char strerr[128];
strerror_r(errno, strerr, sizeof(strerr));
snprintf(cerr->msg, sizeof(cerr->msg), "%s: %s: %s", prefix, prefix2,
strerr);
err->code = GOT_ERR_ERRNO;
err->msg = cerr->msg;
return err;
}
const struct got_error *
got_error_from_errno3(const char *prefix, const char *prefix2,
const char *prefix3)
{
struct got_custom_error *cerr = get_custom_err();
struct got_error *err = &cerr->err;
char strerr[128];
strerror_r(errno, strerr, sizeof(strerr));
snprintf(cerr->msg, sizeof(cerr->msg), "%s: %s: %s: %s", prefix,
prefix2, prefix3, strerr);
err->code = GOT_ERR_ERRNO;
err->msg = cerr->msg;
return err;
}
const struct got_error *
got_error_from_errno_fmt(const char *fmt, ...)
{
struct got_custom_error *cerr = get_custom_err();
struct got_error *err = &cerr->err;
char buf[PATH_MAX * 4];
char strerr[128];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
strerror_r(errno, strerr, sizeof(strerr));
snprintf(cerr->msg, sizeof(cerr->msg), "%s: %s", buf, strerr);
err->code = GOT_ERR_ERRNO;
err->msg = cerr->msg;
return err;
}
const struct got_error *
got_error_set_errno(int code, const char *prefix)
{
errno = code;
return got_error_from_errno(prefix);
}
const struct got_error *
got_ferror(FILE *f, int code)
{
if (ferror(f))
return got_error_from_errno("");
return got_error(code);
}
const struct got_error *
got_error_no_obj(struct got_object_id *id)
{
char msg[sizeof("object not found") + SHA1_DIGEST_STRING_LENGTH];
char id_str[SHA1_DIGEST_STRING_LENGTH];
int ret;
if (!got_sha1_digest_to_str(id->sha1, id_str, sizeof(id_str)))
return got_error(GOT_ERR_NO_OBJ);
ret = snprintf(msg, sizeof(msg), "object %s not found", id_str);
if (ret == -1 || ret >= sizeof(msg))
return got_error(GOT_ERR_NO_OBJ);
return got_error_msg(GOT_ERR_NO_OBJ, msg);
}
const struct got_error *
got_error_not_ref(const char *refname)
{
char msg[sizeof("reference not found") + 1004];
int ret;
ret = snprintf(msg, sizeof(msg), "reference %s not found", refname);
if (ret == -1 || ret >= sizeof(msg))
return got_error(GOT_ERR_NOT_REF);
return got_error_msg(GOT_ERR_NOT_REF, msg);
}
const struct got_error *
got_error_uuid(uint32_t uuid_status, const char *prefix)
{
switch (uuid_status) {
case uuid_s_ok:
return NULL;
case uuid_s_bad_version:
return got_error(GOT_ERR_UUID_VERSION);
case uuid_s_invalid_string_uuid:
return got_error(GOT_ERR_UUID_INVALID);
case uuid_s_no_memory:
return got_error_set_errno(ENOMEM, prefix);
default:
return got_error(GOT_ERR_UUID);
}
}
const struct got_error *
got_error_path(const char *path, int code)
{
struct got_custom_error *cerr = get_custom_err();
struct got_error *err = &cerr->err;
size_t i;
for (i = 0; i < nitems(got_errors); i++) {
if (code == got_errors[i].code) {
err->code = code;
snprintf(cerr->msg, sizeof(cerr->msg), "%s: %s", path,
got_errors[i].msg);
err->msg = cerr->msg;
return err;
}
}
abort();
}
const struct got_error *
got_error_fmt(int code, const char *fmt, ...)
{
struct got_custom_error *cerr = get_custom_err();
struct got_error *err = &cerr->err;
char buf[PATH_MAX * 4];
va_list ap;
size_t i;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
for (i = 0; i < nitems(got_errors); i++) {
if (code == got_errors[i].code) {
err->code = code;
snprintf(cerr->msg, sizeof(cerr->msg), "%s: %s", buf,
got_errors[i].msg);
err->msg = cerr->msg;
return err;
}
}
abort();
}
|
ThomasAdam/gameoftrees
|
lib/got_lib_diff.h
|
<reponame>ThomasAdam/gameoftrees
/*
* Copyright (c) 2020 <NAME> <<EMAIL>>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "arraylist.h"
#include "diff_main.h"
#include "diff_output.h"
enum got_diff_algorithm {
GOT_DIFF_ALGORITHM_MYERS,
GOT_DIFF_ALGORITHM_PATIENCE,
};
enum got_diff_output_format {
GOT_DIFF_OUTPUT_UNIDIFF,
GOT_DIFF_OUTPUT_EDSCRIPT,
};
struct got_diffreg_result {
struct diff_result *result;
FILE *f1;
char *map1;
size_t size1;
FILE *f2;
char *map2;
size_t size2;
struct diff_data left;
struct diff_data right;
};
#define GOT_DIFF_CONFLICT_MARKER_BEGIN "<<<<<<<"
#define GOT_DIFF_CONFLICT_MARKER_ORIG "|||||||"
#define GOT_DIFF_CONFLICT_MARKER_SEP "======="
#define GOT_DIFF_CONFLICT_MARKER_END ">>>>>>>"
const struct got_error *got_diff_get_config(struct diff_config **,
enum got_diff_algorithm, diff_atomize_func_t, void *);
const struct got_error *got_diff_prepare_file(FILE *, char **, size_t *,
struct diff_data *, const struct diff_config *, int, int);
const struct got_error *got_diffreg(struct got_diffreg_result **, FILE *,
FILE *, enum got_diff_algorithm, int, int);
const struct got_error *got_diffreg_output(off_t **, size_t *,
struct got_diffreg_result *, int, int, const char *, const char *,
enum got_diff_output_format, int, FILE *);
const struct got_error *got_diffreg_result_free(struct got_diffreg_result *);
const struct got_error *got_diffreg_result_free_left(
struct got_diffreg_result *);
const struct got_error *got_diffreg_result_free_right(
struct got_diffreg_result *);
const struct got_error *got_diffreg_close(FILE *, char *, size_t,
FILE *, char *, size_t);
const struct got_error *got_merge_diff3(int *, int, const char *, const char *,
const char *, const char *, const char *, const char *);
const struct got_error *got_diff_files(struct got_diffreg_result **, FILE *,
const char *, FILE *, const char *, int, int, int, FILE *);
|
ThomasAdam/gameoftrees
|
lib/got_lib_worktree.h
|
<reponame>ThomasAdam/gameoftrees<filename>lib/got_lib_worktree.h
/*
* Copyright (c) 2018 <NAME> <<EMAIL>>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
struct got_worktree {
char *root_path;
char *repo_path;
int root_fd;
char *path_prefix;
struct got_object_id *base_commit_id;
char *head_ref_name;
uuid_t uuid;
/*
* File descriptor for the lock file, open while a work tree is open.
* When a work tree is opened, a shared lock on the lock file is
* acquired with flock(2). This shared lock is held until the work
* tree is closed, i.e. throughout the lifetime of any operation
* which uses a work tree.
* Before any modifications are made to the on-disk state of work
* tree meta data, tracked files, or directory tree structure, this
* shared lock must be upgraded to an exclusive lock.
*/
int lockfd;
/* Absolute path to worktree's got.conf file. */
char *gotconfig_path;
/* Settings read from got.conf. */
struct got_gotconfig *gotconfig;
};
struct got_commitable {
char *path;
char *in_repo_path;
char *ondisk_path;
unsigned char status;
unsigned char staged_status;
struct got_object_id *blob_id;
struct got_object_id *base_blob_id;
struct got_object_id *staged_blob_id;
struct got_object_id *base_commit_id;
mode_t mode;
int flags;
#define GOT_COMMITABLE_ADDED 0x01
};
#define GOT_WORKTREE_GOT_DIR ".got"
#define GOT_WORKTREE_FILE_INDEX "file-index"
#define GOT_WORKTREE_REPOSITORY "repository"
#define GOT_WORKTREE_PATH_PREFIX "path-prefix"
#define GOT_WORKTREE_HEAD_REF "head-ref"
#define GOT_WORKTREE_BASE_COMMIT "base-commit"
#define GOT_WORKTREE_LOCK "lock"
#define GOT_WORKTREE_FORMAT "format"
#define GOT_WORKTREE_UUID "uuid"
#define GOT_WORKTREE_HISTEDIT_SCRIPT "histedit-script"
#define GOT_WORKTREE_FORMAT_VERSION 1
#define GOT_WORKTREE_INVALID_COMMIT_ID GOT_SHA1_STRING_ZERO
#define GOT_WORKTREE_BASE_REF_PREFIX "refs/got/worktree/base"
const struct got_error *got_worktree_get_base_ref_name(char **,
struct got_worktree *worktree);
/* Temporary branch which accumulates commits during a rebase operation. */
#define GOT_WORKTREE_REBASE_TMP_REF_PREFIX "refs/got/worktree/rebase/tmp"
/* Symbolic reference pointing at the name of the new base branch. */
#define GOT_WORKTREE_NEWBASE_REF_PREFIX "refs/got/worktree/rebase/newbase"
/* Symbolic reference pointing at the name of the branch being rebased. */
#define GOT_WORKTREE_REBASE_BRANCH_REF_PREFIX "refs/got/worktree/rebase/branch"
/* Reference pointing at the ID of the current commit being rebased. */
#define GOT_WORKTREE_REBASE_COMMIT_REF_PREFIX "refs/got/worktree/rebase/commit"
/* Temporary branch which accumulates commits during a histedit operation. */
#define GOT_WORKTREE_HISTEDIT_TMP_REF_PREFIX "refs/got/worktree/histedit/tmp"
/* Symbolic reference pointing at the name of the branch being edited. */
#define GOT_WORKTREE_HISTEDIT_BRANCH_REF_PREFIX \
"refs/got/worktree/histedit/branch"
/* Reference pointing at the ID of the work tree's pre-edit base commit. */
#define GOT_WORKTREE_HISTEDIT_BASE_COMMIT_REF_PREFIX \
"refs/got/worktree/histedit/base-commit"
/* Reference pointing at the ID of the current commit being edited. */
#define GOT_WORKTREE_HISTEDIT_COMMIT_REF_PREFIX \
"refs/got/worktree/histedit/commit"
|
ThomasAdam/gameoftrees
|
gotweb/gotweb.c
|
/*
* Copyright (c) 2019, 2020 <NAME> <<EMAIL>>
* Copyright (c) 2018, 2019 <NAME> <<EMAIL>>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/stat.h>
#include <sys/types.h>
#include <ctype.h>
#include <dirent.h>
#include <err.h>
#include <errno.h>
#include <regex.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <got_error.h>
#include <got_object.h>
#include <got_reference.h>
#include <got_repository.h>
#include <got_path.h>
#include <got_cancel.h>
#include <got_worktree.h>
#include <got_diff.h>
#include <got_commit_graph.h>
#include <got_blame.h>
#include <got_privsep.h>
#include <got_opentemp.h>
#include <kcgi.h>
#include <kcgihtml.h>
#include "gotweb.h"
#ifndef nitems
#define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
#endif
struct gw_trans {
TAILQ_HEAD(headers, gw_header) gw_headers;
TAILQ_HEAD(dirs, gw_dir) gw_dirs;
struct got_repository *repo;
struct gw_dir *gw_dir;
struct gotweb_config *gw_conf;
struct ktemplate *gw_tmpl;
struct khtmlreq *gw_html_req;
struct kreq *gw_req;
const struct got_error *error;
const char *repo_name;
char *repo_path;
char *commit_id;
char *next_id;
char *next_prev_id;
char *prev_id;
char *prev_prev_id;
const char *repo_file;
char *repo_folder;
const char *headref;
unsigned int action;
unsigned int page;
unsigned int repos_total;
enum kmime mime;
};
struct gw_header {
TAILQ_ENTRY(gw_header) entry;
struct got_reflist_head refs;
char *path;
char *refs_str;
char *commit_id; /* id_str1 */
char *parent_id; /* id_str2 */
char *tree_id;
char *author;
char *committer;
char *commit_msg;
time_t committer_time;
};
struct gw_dir {
TAILQ_ENTRY(gw_dir) entry;
char *name;
char *owner;
char *description;
char *url;
char *age;
char *path;
};
enum gw_key {
KEY_ACTION,
KEY_COMMIT_ID,
KEY_FILE,
KEY_FOLDER,
KEY_HEADREF,
KEY_PAGE,
KEY_PATH,
KEY_PREV_ID,
KEY_PREV_PREV_ID,
KEY__ZMAX
};
enum gw_tmpl {
TEMPL_CONTENT,
TEMPL_HEAD,
TEMPL_HEADER,
TEMPL_SEARCH,
TEMPL_SITEPATH,
TEMPL_SITEOWNER,
TEMPL_TITLE,
TEMPL__MAX
};
enum gw_ref_tm {
TM_DIFF,
TM_LONG,
};
enum gw_tags_type {
TAGBRIEF,
TAGFULL,
};
static const char *const gw_templs[TEMPL__MAX] = {
"content",
"head",
"header",
"search",
"sitepath",
"siteowner",
"title",
};
static const struct kvalid gw_keys[KEY__ZMAX] = {
{ kvalid_stringne, "action" },
{ kvalid_stringne, "commit" },
{ kvalid_stringne, "file" },
{ kvalid_stringne, "folder" },
{ kvalid_stringne, "headref" },
{ kvalid_int, "page" },
{ kvalid_stringne, "path" },
{ kvalid_stringne, "prev" },
{ kvalid_stringne, "prev_prev" },
};
static struct gw_header *gw_init_header(void);
static void gw_free_header(struct gw_header *);
static int gw_template(size_t, void *);
static const struct got_error *gw_error(struct gw_trans *);
static const struct got_error *gw_init_gw_dir(struct gw_dir **, const char *);
static const struct got_error *gw_get_repo_description(char **,
struct gw_trans *, char *);
static const struct got_error *gw_get_repo_owner(char **, struct gw_trans *,
char *);
static const struct got_error *gw_get_time_str(char **, time_t, int);
static const struct got_error *gw_get_repo_age(char **, struct gw_trans *,
char *, const char *, int);
static const struct got_error *gw_output_file_blame(struct gw_trans *,
struct gw_header *);
static const struct got_error *gw_output_blob_buf(struct gw_trans *,
struct gw_header *);
static const struct got_error *gw_output_repo_tree(struct gw_trans *,
struct gw_header *);
static const struct got_error *gw_output_diff(struct gw_trans *,
struct gw_header *);
static const struct got_error *gw_output_repo_tags(struct gw_trans *,
struct gw_header *, int, int);
static const struct got_error *gw_output_repo_heads(struct gw_trans *);
static const struct got_error *gw_output_site_link(struct gw_trans *);
static const struct got_error *gw_get_clone_url(char **, struct gw_trans *,
char *);
static const struct got_error *gw_colordiff_line(struct gw_trans *, char *);
static const struct got_error *gw_gen_commit_header(struct gw_trans *, char *,
char*);
static const struct got_error *gw_gen_diff_header(struct gw_trans *, char *,
char*);
static const struct got_error *gw_gen_author_header(struct gw_trans *,
const char *);
static const struct got_error *gw_gen_age_header(struct gw_trans *,
const char *);
static const struct got_error *gw_gen_committer_header(struct gw_trans *,
const char *);
static const struct got_error *gw_gen_commit_msg_header(struct gw_trans*,
char *);
static const struct got_error *gw_gen_tree_header(struct gw_trans *, char *);
static const struct got_error *gw_display_open(struct gw_trans *, enum khttp,
enum kmime);
static const struct got_error *gw_display_index(struct gw_trans *);
static const struct got_error *gw_get_header(struct gw_trans *,
struct gw_header *, int);
static const struct got_error *gw_get_commits(struct gw_trans *,
struct gw_header *, int,
struct got_object_id *);
static const struct got_error *gw_get_commit(struct gw_trans *,
struct gw_header *,
struct got_commit_object *,
struct got_object_id *);
static const struct got_error *gw_apply_unveil(const char *);
static const struct got_error *gw_blame_cb(void *, int, int,
struct got_object_id *);
static const struct got_error *gw_load_got_paths(struct gw_trans *);
static const struct got_error *gw_load_got_path(struct gw_trans *,
struct gw_dir *);
static const struct got_error *gw_parse_querystring(struct gw_trans *);
static const struct got_error *gw_blame(struct gw_trans *);
static const struct got_error *gw_blob(struct gw_trans *);
static const struct got_error *gw_diff(struct gw_trans *);
static const struct got_error *gw_index(struct gw_trans *);
static const struct got_error *gw_commits(struct gw_trans *);
static const struct got_error *gw_briefs(struct gw_trans *);
static const struct got_error *gw_summary(struct gw_trans *);
static const struct got_error *gw_tree(struct gw_trans *);
static const struct got_error *gw_tag(struct gw_trans *);
static const struct got_error *gw_tags(struct gw_trans *);
struct gw_query_action {
unsigned int func_id;
const char *func_name;
const struct got_error *(*func_main)(struct gw_trans *);
char *template;
};
enum gw_query_actions {
GW_BLAME,
GW_BLOB,
GW_BRIEFS,
GW_COMMITS,
GW_DIFF,
GW_ERR,
GW_INDEX,
GW_SUMMARY,
GW_TAG,
GW_TAGS,
GW_TREE,
};
static struct gw_query_action gw_query_funcs[] = {
{ GW_BLAME, "blame", gw_blame, "gw_tmpl/blame.tmpl" },
{ GW_BLOB, "blob", NULL, NULL },
{ GW_BRIEFS, "briefs", gw_briefs, "gw_tmpl/briefs.tmpl" },
{ GW_COMMITS, "commits", gw_commits, "gw_tmpl/commit.tmpl" },
{ GW_DIFF, "diff", gw_diff, "gw_tmpl/diff.tmpl" },
{ GW_ERR, "error", gw_error, "gw_tmpl/err.tmpl" },
{ GW_INDEX, "index", gw_index, "gw_tmpl/index.tmpl" },
{ GW_SUMMARY, "summary", gw_summary, "gw_tmpl/summry.tmpl" },
{ GW_TAG, "tag", gw_tag, "gw_tmpl/tag.tmpl" },
{ GW_TAGS, "tags", gw_tags, "gw_tmpl/tags.tmpl" },
{ GW_TREE, "tree", gw_tree, "gw_tmpl/tree.tmpl" },
};
static const char *
gw_get_action_name(struct gw_trans *gw_trans)
{
return gw_query_funcs[gw_trans->action].func_name;
}
static const struct got_error *
gw_kcgi_error(enum kcgi_err kerr)
{
if (kerr == KCGI_OK)
return NULL;
if (kerr == KCGI_EXIT || kerr == KCGI_HUP)
return got_error(GOT_ERR_CANCELLED);
if (kerr == KCGI_ENOMEM)
return got_error_set_errno(ENOMEM,
kcgi_strerror(kerr));
if (kerr == KCGI_ENFILE)
return got_error_set_errno(ENFILE,
kcgi_strerror(kerr));
if (kerr == KCGI_EAGAIN)
return got_error_set_errno(EAGAIN,
kcgi_strerror(kerr));
if (kerr == KCGI_FORM)
return got_error_msg(GOT_ERR_IO,
kcgi_strerror(kerr));
return got_error_from_errno(kcgi_strerror(kerr));
}
static const struct got_error *
gw_apply_unveil(const char *repo_path)
{
const struct got_error *err;
if (repo_path && unveil(repo_path, "r") != 0)
return got_error_from_errno2("unveil", repo_path);
if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
err = got_privsep_unveil_exec_helpers();
if (err != NULL)
return err;
if (unveil(NULL, NULL) != 0)
return got_error_from_errno("unveil");
return NULL;
}
static int
isbinary(const uint8_t *buf, size_t n)
{
size_t i;
for (i = 0; i < n; i++)
if (buf[i] == 0)
return 1;
return 0;
}
static const struct got_error *
gw_blame(struct gw_trans *gw_trans)
{
const struct got_error *error = NULL;
struct gw_header *header = NULL;
char *age = NULL;
enum kcgi_err kerr = KCGI_OK;
if (pledge("stdio rpath wpath cpath proc exec sendfd unveil",
NULL) == -1)
return got_error_from_errno("pledge");
if ((header = gw_init_header()) == NULL)
return got_error_from_errno("malloc");
error = gw_apply_unveil(gw_trans->gw_dir->path);
if (error)
goto done;
/* check querystring */
if (gw_trans->repo_file == NULL) {
error = got_error_msg(GOT_ERR_QUERYSTRING,
"file required in querystring");
goto done;
}
if (gw_trans->commit_id == NULL) {
error = got_error_msg(GOT_ERR_QUERYSTRING,
"commit required in querystring");
goto done;
}
error = gw_get_header(gw_trans, header, 1);
if (error)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"blame_header_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"blame_header", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
error = gw_get_time_str(&age, header->committer_time,
TM_LONG);
if (error)
goto done;
error = gw_gen_age_header(gw_trans, age ?age : "");
if (error)
goto done;
error = gw_gen_commit_msg_header(gw_trans, header->commit_msg);
if (error)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 2);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"dotted_line", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"blame", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
error = gw_output_file_blame(gw_trans, header);
if (error)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 2);
done:
gw_free_header(header);
if (error == NULL && kerr != KCGI_OK)
error = gw_kcgi_error(kerr);
return error;
}
static const struct got_error *
gw_blob(struct gw_trans *gw_trans)
{
const struct got_error *error = NULL, *err = NULL;
struct gw_header *header = NULL;
enum kcgi_err kerr = KCGI_OK;
if (pledge("stdio rpath wpath cpath proc exec sendfd unveil",
NULL) == -1)
return got_error_from_errno("pledge");
if ((header = gw_init_header()) == NULL)
return got_error_from_errno("malloc");
error = gw_apply_unveil(gw_trans->gw_dir->path);
if (error)
goto done;
/* check querystring */
if (gw_trans->repo_file == NULL) {
error = got_error_msg(GOT_ERR_QUERYSTRING,
"file required in querystring");
goto done;
}
if (gw_trans->commit_id == NULL) {
error = got_error_msg(GOT_ERR_QUERYSTRING,
"commit required in querystring");
goto done;
}
error = gw_get_header(gw_trans, header, 1);
if (error)
goto done;
error = gw_output_blob_buf(gw_trans, header);
done:
if (error) {
gw_trans->mime = KMIME_TEXT_PLAIN;
err = gw_display_index(gw_trans);
if (err) {
error = err;
goto errored;
}
kerr = khttp_puts(gw_trans->gw_req, error->msg);
}
errored:
gw_free_header(header);
if (error == NULL && kerr != KCGI_OK)
error = gw_kcgi_error(kerr);
return error;
}
static const struct got_error *
gw_diff(struct gw_trans *gw_trans)
{
const struct got_error *error = NULL;
struct gw_header *header = NULL;
char *age = NULL;
enum kcgi_err kerr = KCGI_OK;
if (pledge("stdio rpath wpath cpath proc exec sendfd unveil",
NULL) == -1)
return got_error_from_errno("pledge");
if ((header = gw_init_header()) == NULL)
return got_error_from_errno("malloc");
error = gw_apply_unveil(gw_trans->gw_dir->path);
if (error)
goto done;
error = gw_get_header(gw_trans, header, 1);
if (error)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"diff_header_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"diff_header", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
error = gw_gen_diff_header(gw_trans, header->parent_id,
header->commit_id);
if (error)
goto done;
error = gw_gen_commit_header(gw_trans, header->commit_id,
header->refs_str);
if (error)
goto done;
error = gw_gen_tree_header(gw_trans, header->tree_id);
if (error)
goto done;
error = gw_gen_author_header(gw_trans, header->author);
if (error)
goto done;
error = gw_gen_committer_header(gw_trans, header->author);
if (error)
goto done;
error = gw_get_time_str(&age, header->committer_time,
TM_LONG);
if (error)
goto done;
error = gw_gen_age_header(gw_trans, age ?age : "");
if (error)
goto done;
error = gw_gen_commit_msg_header(gw_trans, header->commit_msg);
if (error)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 2);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"dotted_line", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"diff", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
error = gw_output_diff(gw_trans, header);
if (error)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
done:
gw_free_header(header);
free(age);
if (error == NULL && kerr != KCGI_OK)
error = gw_kcgi_error(kerr);
return error;
}
static const struct got_error *
gw_index(struct gw_trans *gw_trans)
{
const struct got_error *error = NULL;
struct gw_dir *gw_dir = NULL;
char *href_next = NULL, *href_prev = NULL, *href_summary = NULL;
char *href_briefs = NULL, *href_commits = NULL, *href_tree = NULL;
char *href_tags = NULL;
unsigned int prev_disp = 0, next_disp = 1, dir_c = 0;
enum kcgi_err kerr = KCGI_OK;
if (pledge("stdio rpath proc exec sendfd unveil",
NULL) == -1) {
error = got_error_from_errno("pledge");
return error;
}
error = gw_apply_unveil(gw_trans->gw_conf->got_repos_path);
if (error)
return error;
error = gw_load_got_paths(gw_trans);
if (error)
return error;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"index_header", KATTR__MAX);
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"index_header_project", KATTR__MAX);
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
kerr = khtml_puts(gw_trans->gw_html_req, "Project");
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
if (gw_trans->gw_conf->got_show_repo_description) {
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"index_header_description", KATTR__MAX);
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
kerr = khtml_puts(gw_trans->gw_html_req, "Description");
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
}
if (gw_trans->gw_conf->got_show_repo_owner) {
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"index_header_owner", KATTR__MAX);
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
kerr = khtml_puts(gw_trans->gw_html_req, "Owner");
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
}
if (gw_trans->gw_conf->got_show_repo_age) {
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"index_header_age", KATTR__MAX);
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
kerr = khtml_puts(gw_trans->gw_html_req, "Last Change");
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
}
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
if (TAILQ_EMPTY(&gw_trans->gw_dirs)) {
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"index_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
kerr = khtml_printf(gw_trans->gw_html_req,
"No repositories found in %s",
gw_trans->gw_conf->got_repos_path);
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"dotted_line", KATTR__MAX);
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
return error;
}
TAILQ_FOREACH(gw_dir, &gw_trans->gw_dirs, entry)
dir_c++;
TAILQ_FOREACH(gw_dir, &gw_trans->gw_dirs, entry) {
if (gw_trans->page > 0 && (gw_trans->page *
gw_trans->gw_conf->got_max_repos_display) > prev_disp) {
prev_disp++;
continue;
}
prev_disp++;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"index_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
href_summary = khttp_urlpart(NULL, NULL, "gotweb", "path",
gw_dir->name, "action", "summary", NULL);
if (href_summary == NULL) {
error = got_error_from_errno("khttp_urlpart");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"index_project", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A, KATTR_HREF,
href_summary, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, gw_dir->name);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 2);
if (kerr != KCGI_OK)
goto done;
if (gw_trans->gw_conf->got_show_repo_description) {
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "index_project_description", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req,
gw_dir->description ? gw_dir->description : "");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
}
if (gw_trans->gw_conf->got_show_repo_owner) {
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "index_project_owner", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req,
gw_dir->owner ? gw_dir->owner : "");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
}
if (gw_trans->gw_conf->got_show_repo_age) {
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "index_project_age", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req,
gw_dir->age ? gw_dir->age : "");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"navs_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"navs", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A, KATTR_HREF,
href_summary, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "summary");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, " | ");
if (kerr != KCGI_OK)
goto done;
href_briefs = khttp_urlpart(NULL, NULL, "gotweb", "path",
gw_dir->name, "action", "briefs", NULL);
if (href_briefs == NULL) {
error = got_error_from_errno("khttp_urlpart");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A, KATTR_HREF,
href_briefs, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "commit briefs");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
error = gw_kcgi_error(kerr);
kerr = khtml_puts(gw_trans->gw_html_req, " | ");
if (kerr != KCGI_OK)
goto done;
href_commits = khttp_urlpart(NULL, NULL, "gotweb", "path",
gw_dir->name, "action", "commits", NULL);
if (href_commits == NULL) {
error = got_error_from_errno("khttp_urlpart");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A, KATTR_HREF,
href_commits, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "commits");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, " | ");
if (kerr != KCGI_OK)
goto done;
href_tags = khttp_urlpart(NULL, NULL, "gotweb", "path",
gw_dir->name, "action", "tags", NULL);
if (href_tags == NULL) {
error = got_error_from_errno("khttp_urlpart");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A, KATTR_HREF,
href_tags, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "tags");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, " | ");
if (kerr != KCGI_OK)
goto done;
href_tree = khttp_urlpart(NULL, NULL, "gotweb", "path",
gw_dir->name, "action", "tree", NULL);
if (href_tree == NULL) {
error = got_error_from_errno("khttp_urlpart");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A, KATTR_HREF,
href_tree, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "tree");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 4);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"dotted_line", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
free(href_summary);
href_summary = NULL;
free(href_briefs);
href_briefs = NULL;
free(href_commits);
href_commits = NULL;
free(href_tags);
href_tags = NULL;
free(href_tree);
href_tree = NULL;
if (gw_trans->gw_conf->got_max_repos_display == 0)
continue;
if ((next_disp == gw_trans->gw_conf->got_max_repos_display) ||
((gw_trans->gw_conf->got_max_repos_display > 0) &&
(gw_trans->page > 0) &&
(next_disp == gw_trans->gw_conf->got_max_repos_display ||
prev_disp == gw_trans->repos_total))) {
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "np_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "nav_prev", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
}
if ((gw_trans->gw_conf->got_max_repos_display > 0) &&
(gw_trans->page > 0) &&
(next_disp == gw_trans->gw_conf->got_max_repos_display ||
prev_disp == gw_trans->repos_total)) {
href_prev = khttp_urlpartx(NULL, NULL, "gotweb", "page",
KATTRX_INT, (int64_t)(gw_trans->page - 1), NULL);
if (href_prev == NULL) {
error = got_error_from_errno("khttp_urlpartx");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A,
KATTR_HREF, href_prev, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "Previous");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
}
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
if (gw_trans->gw_conf->got_max_repos_display > 0 &&
next_disp == gw_trans->gw_conf->got_max_repos_display &&
dir_c != (gw_trans->page + 1) *
gw_trans->gw_conf->got_max_repos_display) {
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "nav_next", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
href_next = khttp_urlpartx(NULL, NULL, "gotweb", "page",
KATTRX_INT, (int64_t)(gw_trans->page + 1), NULL);
if (href_next == NULL) {
error = got_error_from_errno("khttp_urlpartx");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A,
KATTR_HREF, href_next, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "Next");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 3);
if (kerr != KCGI_OK)
goto done;
next_disp = 0;
break;
}
if ((gw_trans->gw_conf->got_max_repos_display > 0) &&
(gw_trans->page > 0) &&
(next_disp == gw_trans->gw_conf->got_max_repos_display ||
prev_disp == gw_trans->repos_total)) {
kerr = khtml_closeelem(gw_trans->gw_html_req, 2);
if (kerr != KCGI_OK)
goto done;
}
next_disp++;
}
done:
free(href_prev);
free(href_next);
free(href_summary);
free(href_briefs);
free(href_commits);
free(href_tags);
free(href_tree);
if (error == NULL && kerr != KCGI_OK)
error = gw_kcgi_error(kerr);
return error;
}
static const struct got_error *
gw_commits(struct gw_trans *gw_trans)
{
const struct got_error *error = NULL;
struct gw_header *header = NULL, *n_header = NULL;
char *age = NULL, *href_diff = NULL, *href_tree = NULL;
char *href_prev = NULL, *href_next = NULL;
enum kcgi_err kerr = KCGI_OK;
if ((header = gw_init_header()) == NULL)
return got_error_from_errno("malloc");
if (pledge("stdio rpath proc exec sendfd unveil",
NULL) == -1) {
error = got_error_from_errno("pledge");
goto done;
}
error = gw_apply_unveil(gw_trans->gw_dir->path);
if (error)
goto done;
error = gw_get_header(gw_trans, header,
gw_trans->gw_conf->got_max_commits_display);
if (error)
goto done;
TAILQ_FOREACH(n_header, &gw_trans->gw_headers, entry) {
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"commits_line_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
error = gw_gen_commit_header(gw_trans, n_header->commit_id,
n_header->refs_str);
if (error)
goto done;
error = gw_gen_author_header(gw_trans, n_header->author);
if (error)
goto done;
error = gw_gen_committer_header(gw_trans, n_header->author);
if (error)
goto done;
error = gw_get_time_str(&age, n_header->committer_time,
TM_LONG);
if (error)
goto done;
error = gw_gen_age_header(gw_trans, age ?age : "");
if (error)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 2);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"dotted_line", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"commit", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khttp_puts(gw_trans->gw_req, n_header->commit_msg);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
href_diff = khttp_urlpart(NULL, NULL, "gotweb", "path",
gw_trans->repo_name, "action", "diff", "commit",
n_header->commit_id, NULL);
if (href_diff == NULL) {
error = got_error_from_errno("khttp_urlpart");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "navs_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "navs", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A,
KATTR_HREF, href_diff, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "diff");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, " | ");
if (kerr != KCGI_OK)
goto done;
href_tree = khttp_urlpart(NULL, NULL, "gotweb", "path",
gw_trans->repo_name, "action", "tree", "commit",
n_header->commit_id, NULL);
if (href_tree == NULL) {
error = got_error_from_errno("khttp_urlpart");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A,
KATTR_HREF, href_tree, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
khtml_puts(gw_trans->gw_html_req, "tree");
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"solid_line", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 2);
if (kerr != KCGI_OK)
goto done;
free(age);
age = NULL;
}
if (gw_trans->next_id || gw_trans->page > 0) {
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "np_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "nav_prev", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
}
if (gw_trans->page > 0 && gw_trans->prev_id) {
href_prev = khttp_urlpartx(NULL, NULL, "gotweb", "path",
KATTRX_STRING, gw_trans->repo_name, "page",
KATTRX_INT, (int64_t) (gw_trans->page - 1), "action",
KATTRX_STRING, "commits", "commit", KATTRX_STRING,
gw_trans->prev_id ? gw_trans->prev_id : "", "prev",
KATTRX_STRING, gw_trans->prev_prev_id ?
gw_trans->prev_prev_id : "", NULL);
if (href_prev == NULL) {
error = got_error_from_errno("khttp_urlpartx");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A,
KATTR_HREF, href_prev, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "Previous");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
}
if (gw_trans->next_id || gw_trans->page > 0) {
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
}
if (gw_trans->next_id) {
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "nav_next", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
href_next = khttp_urlpartx(NULL, NULL, "gotweb", "path",
KATTRX_STRING, gw_trans->repo_name, "page",
KATTRX_INT, (int64_t) (gw_trans->page + 1), "action",
KATTRX_STRING, "commits", "commit", KATTRX_STRING,
gw_trans->next_id, "prev", KATTRX_STRING,
gw_trans->next_prev_id ? gw_trans->next_prev_id : "",
"prev_prev", KATTRX_STRING, gw_trans->prev_prev_id ?
gw_trans->prev_prev_id : "", NULL);
if (href_next == NULL) {
error = got_error_from_errno("khttp_urlpartx");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A,
KATTR_HREF, href_next, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "Next");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 3);
if (kerr != KCGI_OK)
goto done;
}
if (gw_trans->next_id || gw_trans->page > 0) {
kerr = khtml_closeelem(gw_trans->gw_html_req, 2);
if (kerr != KCGI_OK)
goto done;
}
done:
gw_free_header(header);
TAILQ_FOREACH(n_header, &gw_trans->gw_headers, entry)
gw_free_header(n_header);
free(age);
free(href_next);
free(href_prev);
free(href_diff);
free(href_tree);
if (error == NULL && kerr != KCGI_OK)
error = gw_kcgi_error(kerr);
return error;
}
static const struct got_error *
gw_briefs(struct gw_trans *gw_trans)
{
const struct got_error *error = NULL;
struct gw_header *header = NULL, *n_header = NULL;
char *age = NULL, *href_diff = NULL, *href_tree = NULL;
char *href_prev = NULL, *href_next = NULL;
char *newline, *smallerthan;
enum kcgi_err kerr = KCGI_OK;
if ((header = gw_init_header()) == NULL)
return got_error_from_errno("malloc");
if (pledge("stdio rpath proc exec sendfd unveil",
NULL) == -1) {
error = got_error_from_errno("pledge");
goto done;
}
if (gw_trans->action != GW_SUMMARY) {
error = gw_apply_unveil(gw_trans->gw_dir->path);
if (error)
goto done;
}
if (gw_trans->action == GW_SUMMARY)
error = gw_get_header(gw_trans, header, D_MAXSLCOMMDISP);
else
error = gw_get_header(gw_trans, header,
gw_trans->gw_conf->got_max_commits_display);
if (error)
goto done;
TAILQ_FOREACH(n_header, &gw_trans->gw_headers, entry) {
error = gw_get_time_str(&age, n_header->committer_time,
TM_DIFF);
if (error)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "briefs_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "briefs_age", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, age ? age : "");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "briefs_author", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
smallerthan = strchr(n_header->author, '<');
if (smallerthan)
*smallerthan = '\0';
kerr = khtml_puts(gw_trans->gw_html_req, n_header->author);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
href_diff = khttp_urlpart(NULL, NULL, "gotweb", "path",
gw_trans->repo_name, "action", "diff", "commit",
n_header->commit_id, NULL);
if (href_diff == NULL) {
error = got_error_from_errno("khttp_urlpart");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "briefs_log", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
newline = strchr(n_header->commit_msg, '\n');
if (newline)
*newline = '\0';
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A,
KATTR_HREF, href_diff, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, n_header->commit_msg);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
if (n_header->refs_str) {
kerr = khtml_puts(gw_trans->gw_html_req, " ");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_SPAN,
KATTR_ID, "refs_str", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_printf(gw_trans->gw_html_req, "(%s)",
n_header->refs_str);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
}
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "navs_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "navs", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A,
KATTR_HREF, href_diff, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "diff");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, " | ");
if (kerr != KCGI_OK)
goto done;
href_tree = khttp_urlpart(NULL, NULL, "gotweb", "path",
gw_trans->repo_name, "action", "tree", "commit",
n_header->commit_id, NULL);
if (href_tree == NULL) {
error = got_error_from_errno("khttp_urlpart");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A,
KATTR_HREF, href_tree, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
khtml_puts(gw_trans->gw_html_req, "tree");
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "dotted_line", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 3);
if (kerr != KCGI_OK)
goto done;
free(age);
age = NULL;
free(href_diff);
href_diff = NULL;
free(href_tree);
href_tree = NULL;
}
if (gw_trans->next_id || gw_trans->page > 0) {
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "np_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "nav_prev", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
}
if (gw_trans->page > 0 && gw_trans->prev_id) {
href_prev = khttp_urlpartx(NULL, NULL, "gotweb", "path",
KATTRX_STRING, gw_trans->repo_name, "page",
KATTRX_INT, (int64_t) (gw_trans->page - 1), "action",
KATTRX_STRING, "briefs", "commit", KATTRX_STRING,
gw_trans->prev_id ? gw_trans->prev_id : "", "prev",
KATTRX_STRING, gw_trans->prev_prev_id ?
gw_trans->prev_prev_id : "", NULL);
if (href_prev == NULL) {
error = got_error_from_errno("khttp_urlpartx");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A,
KATTR_HREF, href_prev, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "Previous");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
}
if (gw_trans->next_id || gw_trans->page > 0) {
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
}
if (gw_trans->next_id) {
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "nav_next", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
href_next = khttp_urlpartx(NULL, NULL, "gotweb", "path",
KATTRX_STRING, gw_trans->repo_name, "page",
KATTRX_INT, (int64_t) (gw_trans->page + 1), "action",
KATTRX_STRING, "briefs", "commit", KATTRX_STRING,
gw_trans->next_id, "prev", KATTRX_STRING,
gw_trans->next_prev_id ? gw_trans->next_prev_id : "",
"prev_prev", KATTRX_STRING, gw_trans->prev_id ?
gw_trans->prev_id : "", NULL);
if (href_next == NULL) {
error = got_error_from_errno("khttp_urlpartx");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A,
KATTR_HREF, href_next, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "Next");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 3);
if (kerr != KCGI_OK)
goto done;
}
if (gw_trans->next_id || gw_trans->page > 0) {
kerr = khtml_closeelem(gw_trans->gw_html_req, 2);
if (kerr != KCGI_OK)
goto done;
}
done:
gw_free_header(header);
TAILQ_FOREACH(n_header, &gw_trans->gw_headers, entry)
gw_free_header(n_header);
free(age);
free(href_next);
free(href_prev);
free(href_diff);
free(href_tree);
if (error == NULL && kerr != KCGI_OK)
error = gw_kcgi_error(kerr);
return error;
}
static const struct got_error *
gw_summary(struct gw_trans *gw_trans)
{
const struct got_error *error = NULL;
char *age = NULL;
enum kcgi_err kerr = KCGI_OK;
if (pledge("stdio rpath proc exec sendfd unveil", NULL) == -1)
return got_error_from_errno("pledge");
error = gw_apply_unveil(gw_trans->gw_dir->path);
if (error)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"summary_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
if (gw_trans->gw_conf->got_show_repo_description &&
gw_trans->gw_dir->description != NULL &&
(strcmp(gw_trans->gw_dir->description, "") != 0)) {
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "description_title", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "Description: ");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "description", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req,
gw_trans->gw_dir->description);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
}
if (gw_trans->gw_conf->got_show_repo_owner &&
gw_trans->gw_dir->owner != NULL &&
(strcmp(gw_trans->gw_dir->owner, "") != 0)) {
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "repo_owner_title", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "Owner: ");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "repo_owner", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req,
gw_trans->gw_dir->owner);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
}
if (gw_trans->gw_conf->got_show_repo_age) {
error = gw_get_repo_age(&age, gw_trans, gw_trans->gw_dir->path,
NULL, TM_LONG);
if (error)
goto done;
if (age != NULL) {
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "last_change_title", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req,
"Last Change: ");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "last_change", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, age);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
}
}
if (gw_trans->gw_conf->got_show_repo_cloneurl &&
gw_trans->gw_dir->url != NULL &&
(strcmp(gw_trans->gw_dir->url, "") != 0)) {
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "cloneurl_title", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "Clone URL: ");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "cloneurl", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, gw_trans->gw_dir->url);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
}
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"briefs_title_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"briefs_title", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "Commit Briefs");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 2);
if (kerr != KCGI_OK)
goto done;
error = gw_briefs(gw_trans);
if (error)
goto done;
error = gw_tags(gw_trans);
if (error)
goto done;
error = gw_output_repo_heads(gw_trans);
done:
free(age);
if (error == NULL && kerr != KCGI_OK)
error = gw_kcgi_error(kerr);
return error;
}
static const struct got_error *
gw_tree(struct gw_trans *gw_trans)
{
const struct got_error *error = NULL;
struct gw_header *header = NULL;
char *tree = NULL, *tree_html = NULL, *tree_html_disp = NULL;
char *age = NULL;
enum kcgi_err kerr = KCGI_OK;
if (pledge("stdio rpath proc exec sendfd unveil", NULL) == -1)
return got_error_from_errno("pledge");
if ((header = gw_init_header()) == NULL)
return got_error_from_errno("malloc");
error = gw_apply_unveil(gw_trans->gw_dir->path);
if (error)
goto done;
error = gw_get_header(gw_trans, header, 1);
if (error)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"tree_header_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"tree_header", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
error = gw_gen_tree_header(gw_trans, header->tree_id);
if (error)
goto done;
error = gw_get_time_str(&age, header->committer_time,
TM_LONG);
if (error)
goto done;
error = gw_gen_age_header(gw_trans, age ?age : "");
if (error)
goto done;
error = gw_gen_commit_msg_header(gw_trans, header->commit_msg);
if (error)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 2);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"dotted_line", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"tree", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
error = gw_output_repo_tree(gw_trans, header);
if (error)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
done:
gw_free_header(header);
free(tree_html_disp);
free(tree_html);
free(tree);
free(age);
if (error == NULL && kerr != KCGI_OK)
error = gw_kcgi_error(kerr);
return error;
}
static const struct got_error *
gw_tags(struct gw_trans *gw_trans)
{
const struct got_error *error = NULL;
struct gw_header *header = NULL;
char *href_next = NULL, *href_prev = NULL;
enum kcgi_err kerr = KCGI_OK;
if (pledge("stdio rpath proc exec sendfd unveil", NULL) == -1)
return got_error_from_errno("pledge");
if ((header = gw_init_header()) == NULL)
return got_error_from_errno("malloc");
if (gw_trans->action != GW_SUMMARY) {
error = gw_apply_unveil(gw_trans->gw_dir->path);
if (error)
goto done;
}
error = gw_get_header(gw_trans, header, 1);
if (error)
goto done;
if (gw_trans->action == GW_SUMMARY) {
gw_trans->next_id = NULL;
error = gw_output_repo_tags(gw_trans, header,
D_MAXSLCOMMDISP, TAGBRIEF);
if (error)
goto done;
} else {
error = gw_output_repo_tags(gw_trans, header,
gw_trans->gw_conf->got_max_commits_display, TAGBRIEF);
if (error)
goto done;
}
if (gw_trans->next_id || gw_trans->page > 0) {
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "np_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "nav_prev", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
}
if (gw_trans->page > 0 && gw_trans->prev_id) {
href_prev = khttp_urlpartx(NULL, NULL, "gotweb", "path",
KATTRX_STRING, gw_trans->repo_name, "page",
KATTRX_INT, (int64_t) (gw_trans->page - 1), "action",
KATTRX_STRING, "tags", "commit", KATTRX_STRING,
gw_trans->prev_id ? gw_trans->prev_id : "", "prev",
KATTRX_STRING, gw_trans->prev_prev_id ?
gw_trans->prev_prev_id : "", NULL);
if (href_prev == NULL) {
error = got_error_from_errno("khttp_urlpartx");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A,
KATTR_HREF, href_prev, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "Previous");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
}
if (gw_trans->next_id || gw_trans->page > 0) {
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
}
if (gw_trans->next_id) {
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "nav_next", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
href_next = khttp_urlpartx(NULL, NULL, "gotweb", "path",
KATTRX_STRING, gw_trans->repo_name, "page",
KATTRX_INT, (int64_t) (gw_trans->page + 1), "action",
KATTRX_STRING, "tags", "commit", KATTRX_STRING,
gw_trans->next_id, "prev", KATTRX_STRING,
gw_trans->next_prev_id ? gw_trans->next_prev_id : "",
"prev_prev", KATTRX_STRING, gw_trans->prev_id ?
gw_trans->prev_id : "", NULL);
if (href_next == NULL) {
error = got_error_from_errno("khttp_urlpartx");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A,
KATTR_HREF, href_next, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "Next");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 3);
if (kerr != KCGI_OK)
goto done;
}
if (gw_trans->next_id || gw_trans->page > 0) {
kerr = khtml_closeelem(gw_trans->gw_html_req, 2);
if (kerr != KCGI_OK)
goto done;
}
done:
gw_free_header(header);
free(href_next);
free(href_prev);
if (error == NULL && kerr != KCGI_OK)
error = gw_kcgi_error(kerr);
return error;
}
static const struct got_error *
gw_tag(struct gw_trans *gw_trans)
{
const struct got_error *error = NULL;
struct gw_header *header = NULL;
enum kcgi_err kerr = KCGI_OK;
if (pledge("stdio rpath proc exec sendfd unveil", NULL) == -1)
return got_error_from_errno("pledge");
if ((header = gw_init_header()) == NULL)
return got_error_from_errno("malloc");
error = gw_apply_unveil(gw_trans->gw_dir->path);
if (error)
goto done;
if (gw_trans->commit_id == NULL) {
error = got_error_msg(GOT_ERR_QUERYSTRING,
"commit required in querystring");
goto done;
}
error = gw_get_header(gw_trans, header, 1);
if (error)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"tag_header_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"tag_header", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
error = gw_gen_commit_header(gw_trans, header->commit_id,
header->refs_str);
if (error)
goto done;
error = gw_gen_commit_msg_header(gw_trans, header->commit_msg);
if (error)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 2);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"dotted_line", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"tree", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
error = gw_output_repo_tags(gw_trans, header, 1, TAGFULL);
if (error)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
done:
gw_free_header(header);
if (error == NULL && kerr != KCGI_OK)
error = gw_kcgi_error(kerr);
return error;
}
static const struct got_error *
gw_load_got_path(struct gw_trans *gw_trans, struct gw_dir *gw_dir)
{
const struct got_error *error = NULL;
DIR *dt;
char *dir_test;
int opened = 0;
if (asprintf(&dir_test, "%s/%s/%s",
gw_trans->gw_conf->got_repos_path, gw_dir->name,
GOTWEB_GIT_DIR) == -1)
return got_error_from_errno("asprintf");
dt = opendir(dir_test);
if (dt == NULL) {
free(dir_test);
} else {
gw_dir->path = strdup(dir_test);
if (gw_dir->path == NULL) {
opened = 1;
error = got_error_from_errno("strdup");
goto errored;
}
opened = 1;
goto done;
}
if (asprintf(&dir_test, "%s/%s/%s",
gw_trans->gw_conf->got_repos_path, gw_dir->name,
GOTWEB_GOT_DIR) == -1) {
dir_test = NULL;
error = got_error_from_errno("asprintf");
goto errored;
}
dt = opendir(dir_test);
if (dt == NULL)
free(dir_test);
else {
opened = 1;
error = got_error(GOT_ERR_NOT_GIT_REPO);
goto errored;
}
if (asprintf(&dir_test, "%s/%s",
gw_trans->gw_conf->got_repos_path, gw_dir->name) == -1) {
error = got_error_from_errno("asprintf");
dir_test = NULL;
goto errored;
}
gw_dir->path = strdup(dir_test);
if (gw_dir->path == NULL) {
opened = 1;
error = got_error_from_errno("strdup");
goto errored;
}
dt = opendir(dir_test);
if (dt == NULL) {
error = got_error_path(gw_dir->name, GOT_ERR_NOT_GIT_REPO);
goto errored;
} else
opened = 1;
done:
error = gw_get_repo_description(&gw_dir->description, gw_trans,
gw_dir->path);
if (error)
goto errored;
error = gw_get_repo_owner(&gw_dir->owner, gw_trans, gw_dir->path);
if (error)
goto errored;
error = gw_get_repo_age(&gw_dir->age, gw_trans, gw_dir->path,
NULL, TM_DIFF);
if (error)
goto errored;
error = gw_get_clone_url(&gw_dir->url, gw_trans, gw_dir->path);
errored:
free(dir_test);
if (opened)
if (dt && closedir(dt) == -1 && error == NULL)
error = got_error_from_errno("closedir");
return error;
}
static const struct got_error *
gw_load_got_paths(struct gw_trans *gw_trans)
{
const struct got_error *error = NULL;
DIR *d;
struct dirent **sd_dent;
struct gw_dir *gw_dir;
struct stat st;
unsigned int d_cnt, d_i;
d = opendir(gw_trans->gw_conf->got_repos_path);
if (d == NULL) {
error = got_error_from_errno2("opendir",
gw_trans->gw_conf->got_repos_path);
return error;
}
d_cnt = scandir(gw_trans->gw_conf->got_repos_path, &sd_dent, NULL,
alphasort);
if (d_cnt == -1) {
error = got_error_from_errno2("scandir",
gw_trans->gw_conf->got_repos_path);
goto done;
}
for (d_i = 0; d_i < d_cnt; d_i++) {
if (gw_trans->gw_conf->got_max_repos > 0 &&
(d_i - 2) == gw_trans->gw_conf->got_max_repos)
break; /* account for parent and self */
if (strcmp(sd_dent[d_i]->d_name, ".") == 0 ||
strcmp(sd_dent[d_i]->d_name, "..") == 0)
continue;
error = gw_init_gw_dir(&gw_dir, sd_dent[d_i]->d_name);
if (error)
goto done;
error = gw_load_got_path(gw_trans, gw_dir);
if (error && error->code == GOT_ERR_NOT_GIT_REPO) {
error = NULL;
continue;
}
else if (error)
goto done;
if (lstat(gw_dir->path, &st) == 0 && S_ISDIR(st.st_mode) &&
!got_path_dir_is_empty(gw_dir->path)) {
TAILQ_INSERT_TAIL(&gw_trans->gw_dirs, gw_dir,
entry);
gw_trans->repos_total++;
}
}
done:
if (d && closedir(d) == -1 && error == NULL)
error = got_error_from_errno("closedir");
return error;
}
static const struct got_error *
gw_parse_querystring(struct gw_trans *gw_trans)
{
const struct got_error *error = NULL;
struct kpair *p;
struct gw_query_action *action = NULL;
unsigned int i;
if (gw_trans->gw_req->fieldnmap[0]) {
return got_error(GOT_ERR_QUERYSTRING);
} else if ((p = gw_trans->gw_req->fieldmap[KEY_PATH])) {
/* define gw_trans->repo_path */
gw_trans->repo_name = p->parsed.s;
if (asprintf(&gw_trans->repo_path, "%s/%s",
gw_trans->gw_conf->got_repos_path, p->parsed.s) == -1)
return got_error_from_errno("asprintf");
/* get action and set function */
if ((p = gw_trans->gw_req->fieldmap[KEY_ACTION])) {
for (i = 0; i < nitems(gw_query_funcs); i++) {
action = &gw_query_funcs[i];
if (action->func_name == NULL)
continue;
if (strcmp(action->func_name,
p->parsed.s) == 0) {
gw_trans->action = i;
break;
}
}
}
if (gw_trans->action == -1) {
gw_trans->action = GW_ERR;
gw_trans->error = got_error_msg(GOT_ERR_QUERYSTRING,
p != NULL ? "bad action in querystring" :
"no action in querystring");
return error;
}
if ((p = gw_trans->gw_req->fieldmap[KEY_COMMIT_ID])) {
if (asprintf(&gw_trans->commit_id, "%s",
p->parsed.s) == -1)
return got_error_from_errno("asprintf");
}
if ((p = gw_trans->gw_req->fieldmap[KEY_FILE]))
gw_trans->repo_file = p->parsed.s;
if ((p = gw_trans->gw_req->fieldmap[KEY_FOLDER])) {
if (asprintf(&gw_trans->repo_folder, "%s",
p->parsed.s) == -1)
return got_error_from_errno("asprintf");
}
if ((p = gw_trans->gw_req->fieldmap[KEY_PREV_ID])) {
if (asprintf(&gw_trans->prev_id, "%s",
p->parsed.s) == -1)
return got_error_from_errno("asprintf");
}
if ((p = gw_trans->gw_req->fieldmap[KEY_PREV_PREV_ID])) {
if (asprintf(&gw_trans->prev_prev_id, "%s",
p->parsed.s) == -1)
return got_error_from_errno("asprintf");
}
if ((p = gw_trans->gw_req->fieldmap[KEY_HEADREF]))
gw_trans->headref = p->parsed.s;
error = gw_init_gw_dir(&gw_trans->gw_dir, gw_trans->repo_name);
if (error)
return error;
gw_trans->error = gw_load_got_path(gw_trans, gw_trans->gw_dir);
} else
gw_trans->action = GW_INDEX;
if ((p = gw_trans->gw_req->fieldmap[KEY_PAGE]))
gw_trans->page = p->parsed.i;
return error;
}
static const struct got_error *
gw_init_gw_dir(struct gw_dir **gw_dir, const char *dir)
{
const struct got_error *error;
*gw_dir = malloc(sizeof(**gw_dir));
if (*gw_dir == NULL)
return got_error_from_errno("malloc");
if (asprintf(&(*gw_dir)->name, "%s", dir) == -1) {
error = got_error_from_errno("asprintf");
free(*gw_dir);
*gw_dir = NULL;
return error;
}
return NULL;
}
static const struct got_error *
gw_display_open(struct gw_trans *gw_trans, enum khttp code, enum kmime mime)
{
enum kcgi_err kerr = KCGI_OK;
kerr = khttp_head(gw_trans->gw_req, kresps[KRESP_ALLOW], "GET");
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
kerr = khttp_head(gw_trans->gw_req, kresps[KRESP_STATUS], "%s",
khttps[code]);
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
kerr = khttp_head(gw_trans->gw_req, kresps[KRESP_CONTENT_TYPE], "%s",
kmimetypes[mime]);
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
kerr = khttp_head(gw_trans->gw_req, "X-Content-Type-Options",
"nosniff");
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
kerr = khttp_head(gw_trans->gw_req, "X-Frame-Options", "DENY");
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
kerr = khttp_head(gw_trans->gw_req, "X-XSS-Protection",
"1; mode=block");
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
if (gw_trans->mime == KMIME_APP_OCTET_STREAM) {
kerr = khttp_head(gw_trans->gw_req,
kresps[KRESP_CONTENT_DISPOSITION],
"attachment; filename=%s", gw_trans->repo_file);
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
}
kerr = khttp_body(gw_trans->gw_req);
return gw_kcgi_error(kerr);
}
static const struct got_error *
gw_display_index(struct gw_trans *gw_trans)
{
const struct got_error *error;
enum kcgi_err kerr = KCGI_OK;
/* catch early querystring errors */
if (gw_trans->error)
gw_trans->action = GW_ERR;
error = gw_display_open(gw_trans, KHTTP_200, gw_trans->mime);
if (error)
return error;
kerr = khtml_open(gw_trans->gw_html_req, gw_trans->gw_req, 0);
if (kerr != KCGI_OK)
return gw_kcgi_error(kerr);
if (gw_trans->action != GW_BLOB) {
kerr = khttp_template(gw_trans->gw_req, gw_trans->gw_tmpl,
gw_query_funcs[gw_trans->action].template);
if (kerr != KCGI_OK) {
khtml_close(gw_trans->gw_html_req);
return gw_kcgi_error(kerr);
}
}
return gw_kcgi_error(khtml_close(gw_trans->gw_html_req));
}
static const struct got_error *
gw_error(struct gw_trans *gw_trans)
{
enum kcgi_err kerr = KCGI_OK;
kerr = khtml_puts(gw_trans->gw_html_req, gw_trans->error->msg);
return gw_kcgi_error(kerr);
}
static int
gw_template(size_t key, void *arg)
{
const struct got_error *error = NULL;
enum kcgi_err kerr = KCGI_OK;
struct gw_trans *gw_trans = arg;
char *ati = NULL, *fic32 = NULL, *fic16 = NULL;
char *swm = NULL, *spt = NULL, *css = NULL, *logo = NULL;
if (asprintf(&ati, "%s%s", gw_trans->gw_conf->got_www_path,
"/apple-touch-icon.png") == -1)
goto err;
if (asprintf(&fic32, "%s%s", gw_trans->gw_conf->got_www_path,
"/favicon-32x32.png") == -1)
goto err;
if (asprintf(&fic16, "%s%s", gw_trans->gw_conf->got_www_path,
"/favicon-16x16.png") == -1)
goto err;
if (asprintf(&swm, "%s%s", gw_trans->gw_conf->got_www_path,
"/site.webmanifest") == -1)
goto err;
if (asprintf(&spt, "%s%s", gw_trans->gw_conf->got_www_path,
"/safari-pinned-tab.svg") == -1)
goto err;
if (asprintf(&css, "%s%s", gw_trans->gw_conf->got_www_path,
"/gotweb.css") == -1)
goto err;
if (asprintf(&logo, "%s%s%s", gw_trans->gw_conf->got_www_path,
gw_trans->gw_conf->got_www_path ? "/" : "",
gw_trans->gw_conf->got_logo) == -1)
goto err;
switch (key) {
case (TEMPL_HEAD):
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_META,
KATTR_NAME, "viewport",
KATTR_CONTENT, "initial-scale=.75, user-scalable=yes",
KATTR__MAX);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_META,
KATTR_CHARSET, "utf-8",
KATTR__MAX);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_META,
KATTR_NAME, "msapplication-TileColor",
KATTR_CONTENT, "#da532c", KATTR__MAX);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_META,
KATTR_NAME, "theme-color",
KATTR_CONTENT, "#ffffff", KATTR__MAX);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_LINK,
KATTR_REL, "apple-touch-icon", KATTR_SIZES, "180x180",
KATTR_HREF, ati, KATTR__MAX);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_LINK,
KATTR_REL, "icon", KATTR_TYPE, "image/png", KATTR_SIZES,
"32x32", KATTR_HREF, fic32, KATTR__MAX);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_LINK,
KATTR_REL, "icon", KATTR_TYPE, "image/png", KATTR_SIZES,
"16x16", KATTR_HREF, fic16, KATTR__MAX);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_LINK,
KATTR_REL, "manifest", KATTR_HREF, swm,
KATTR__MAX);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_LINK,
KATTR_REL, "mask-icon", KATTR_HREF,
spt, KATTR__MAX);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_LINK,
KATTR_REL, "stylesheet", KATTR_TYPE, "text/css",
KATTR_HREF, css, KATTR__MAX);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
return 0;
break;
case(TEMPL_HEADER):
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "got_link", KATTR__MAX);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A,
KATTR_HREF, gw_trans->gw_conf->got_logo_url,
KATTR_TARGET, "_sotd", KATTR__MAX);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_IMG,
KATTR_SRC, logo, KATTR__MAX);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_closeelem(gw_trans->gw_html_req, 3);
if (kerr != KCGI_OK)
return 0;
break;
case (TEMPL_SITEPATH):
error = gw_output_site_link(gw_trans);
if (error)
return 0;
break;
case(TEMPL_TITLE):
if (gw_trans->gw_conf->got_site_name != NULL) {
kerr = khtml_puts(gw_trans->gw_html_req,
gw_trans->gw_conf->got_site_name);
if (kerr != KCGI_OK)
return 0;
}
break;
case (TEMPL_SEARCH):
break;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"search", KATTR__MAX);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_FORM,
KATTR_METHOD, "POST", KATTR__MAX);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_INPUT, KATTR_ID,
"got-search", KATTR_NAME, "got-search", KATTR_SIZE, "15",
KATTR_MAXLENGTH, "50", KATTR__MAX);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_BUTTON,
KATTR__MAX);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_puts(gw_trans->gw_html_req, "Search");
if (kerr != KCGI_OK)
return 0;
kerr = khtml_closeelem(gw_trans->gw_html_req, 4);
if (kerr != KCGI_OK)
return 0;
break;
case(TEMPL_SITEOWNER):
if (gw_trans->gw_conf->got_site_owner != NULL &&
gw_trans->gw_conf->got_show_site_owner) {
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "site_owner_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "site_owner", KATTR__MAX);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_puts(gw_trans->gw_html_req,
gw_trans->gw_conf->got_site_owner);
kerr = khtml_closeelem(gw_trans->gw_html_req, 2);
if (kerr != KCGI_OK)
return 0;
}
break;
case(TEMPL_CONTENT):
error = gw_query_funcs[gw_trans->action].func_main(gw_trans);
if (error) {
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "tmpl_err", KATTR__MAX);
if (kerr != KCGI_OK)
return 0;
kerr = khttp_printf(gw_trans->gw_req, "Error: %s",
error->msg);
if (kerr != KCGI_OK)
return 0;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
return 0;
}
break;
default:
return 0;
}
free(ati);
free(fic32);
free(fic16);
free(swm);
free(spt);
free(css);
free(logo);
return 1;
err:
free(ati);
free(fic32);
free(fic16);
free(swm);
free(spt);
free(css);
free(logo);
return 0;
}
static const struct got_error *
gw_gen_commit_header(struct gw_trans *gw_trans, char *str1, char *str2)
{
const struct got_error *error = NULL;
enum kcgi_err kerr = KCGI_OK;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "header_commit_title", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "Commit: ");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "header_commit", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_printf(gw_trans->gw_html_req, "%s ", str1);
if (kerr != KCGI_OK)
goto done;
if (str2 != NULL) {
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_SPAN,
KATTR_ID, "refs_str", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_printf(gw_trans->gw_html_req, "(%s)", str2);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
}
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
done:
if (error == NULL && kerr != KCGI_OK)
error = gw_kcgi_error(kerr);
return error;
}
static const struct got_error *
gw_gen_diff_header(struct gw_trans *gw_trans, char *str1, char *str2)
{
const struct got_error *error = NULL;
enum kcgi_err kerr = KCGI_OK;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "header_diff_title", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "Diff: ");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "header_diff", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
if (str1 != NULL) {
kerr = khtml_puts(gw_trans->gw_html_req, str1);
if (kerr != KCGI_OK)
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_BR, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, str2);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
done:
if (error == NULL && kerr != KCGI_OK)
error = gw_kcgi_error(kerr);
return error;
}
static const struct got_error *
gw_gen_age_header(struct gw_trans *gw_trans, const char *str)
{
const struct got_error *error = NULL;
enum kcgi_err kerr = KCGI_OK;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "header_age_title", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "Date: ");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "header_age", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, str);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
done:
if (error == NULL && kerr != KCGI_OK)
error = gw_kcgi_error(kerr);
return error;
}
static const struct got_error *
gw_gen_author_header(struct gw_trans *gw_trans, const char *str)
{
const struct got_error *error = NULL;
enum kcgi_err kerr = KCGI_OK;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "header_author_title", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "Author: ");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "header_author", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, str);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
done:
if (error == NULL && kerr != KCGI_OK)
error = gw_kcgi_error(kerr);
return error;
}
static const struct got_error *
gw_gen_committer_header(struct gw_trans *gw_trans, const char *str)
{
const struct got_error *error = NULL;
enum kcgi_err kerr = KCGI_OK;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "header_committer_title", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "Committer: ");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "header_committer", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, str);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
done:
if (error == NULL && kerr != KCGI_OK)
error = gw_kcgi_error(kerr);
return error;
}
static const struct got_error *
gw_gen_commit_msg_header(struct gw_trans *gw_trans, char *str)
{
const struct got_error *error = NULL;
enum kcgi_err kerr = KCGI_OK;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "header_commit_msg_title", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "Message: ");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "header_commit_msg", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khttp_puts(gw_trans->gw_req, str);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
done:
if (error == NULL && kerr != KCGI_OK)
error = gw_kcgi_error(kerr);
return error;
}
static const struct got_error *
gw_gen_tree_header(struct gw_trans *gw_trans, char *str)
{
const struct got_error *error = NULL;
enum kcgi_err kerr = KCGI_OK;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "header_tree_title", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "Tree: ");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "header_tree", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, str);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
done:
if (error == NULL && kerr != KCGI_OK)
error = gw_kcgi_error(kerr);
return error;
}
static const struct got_error *
gw_get_repo_description(char **description, struct gw_trans *gw_trans,
char *dir)
{
const struct got_error *error = NULL;
FILE *f = NULL;
char *d_file = NULL;
unsigned int len;
size_t n;
*description = NULL;
if (gw_trans->gw_conf->got_show_repo_description == 0)
return NULL;
if (asprintf(&d_file, "%s/description", dir) == -1)
return got_error_from_errno("asprintf");
f = fopen(d_file, "r");
if (f == NULL) {
if (errno == ENOENT || errno == EACCES)
return NULL;
error = got_error_from_errno2("fopen", d_file);
goto done;
}
if (fseek(f, 0, SEEK_END) == -1) {
error = got_ferror(f, GOT_ERR_IO);
goto done;
}
len = ftell(f);
if (len == -1) {
error = got_ferror(f, GOT_ERR_IO);
goto done;
}
if (fseek(f, 0, SEEK_SET) == -1) {
error = got_ferror(f, GOT_ERR_IO);
goto done;
}
*description = calloc(len + 1, sizeof(**description));
if (*description == NULL) {
error = got_error_from_errno("calloc");
goto done;
}
n = fread(*description, 1, len, f);
if (n == 0 && ferror(f))
error = got_ferror(f, GOT_ERR_IO);
done:
if (f != NULL && fclose(f) == -1 && error == NULL)
error = got_error_from_errno("fclose");
free(d_file);
return error;
}
static const struct got_error *
gw_get_time_str(char **repo_age, time_t committer_time, int ref_tm)
{
struct tm tm;
time_t diff_time;
char *years = "years ago", *months = "months ago";
char *weeks = "weeks ago", *days = "days ago", *hours = "hours ago";
char *minutes = "minutes ago", *seconds = "seconds ago";
char *now = "right now";
char *s;
char datebuf[29];
*repo_age = NULL;
switch (ref_tm) {
case TM_DIFF:
diff_time = time(NULL) - committer_time;
if (diff_time > 60 * 60 * 24 * 365 * 2) {
if (asprintf(repo_age, "%lld %s",
(diff_time / 60 / 60 / 24 / 365), years) == -1)
return got_error_from_errno("asprintf");
} else if (diff_time > 60 * 60 * 24 * (365 / 12) * 2) {
if (asprintf(repo_age, "%lld %s",
(diff_time / 60 / 60 / 24 / (365 / 12)),
months) == -1)
return got_error_from_errno("asprintf");
} else if (diff_time > 60 * 60 * 24 * 7 * 2) {
if (asprintf(repo_age, "%lld %s",
(diff_time / 60 / 60 / 24 / 7), weeks) == -1)
return got_error_from_errno("asprintf");
} else if (diff_time > 60 * 60 * 24 * 2) {
if (asprintf(repo_age, "%lld %s",
(diff_time / 60 / 60 / 24), days) == -1)
return got_error_from_errno("asprintf");
} else if (diff_time > 60 * 60 * 2) {
if (asprintf(repo_age, "%lld %s",
(diff_time / 60 / 60), hours) == -1)
return got_error_from_errno("asprintf");
} else if (diff_time > 60 * 2) {
if (asprintf(repo_age, "%lld %s", (diff_time / 60),
minutes) == -1)
return got_error_from_errno("asprintf");
} else if (diff_time > 2) {
if (asprintf(repo_age, "%lld %s", diff_time,
seconds) == -1)
return got_error_from_errno("asprintf");
} else {
if (asprintf(repo_age, "%s", now) == -1)
return got_error_from_errno("asprintf");
}
break;
case TM_LONG:
if (gmtime_r(&committer_time, &tm) == NULL)
return got_error_from_errno("gmtime_r");
s = asctime_r(&tm, datebuf);
if (s == NULL)
return got_error_from_errno("asctime_r");
if (asprintf(repo_age, "%s UTC", datebuf) == -1)
return got_error_from_errno("asprintf");
break;
}
return NULL;
}
static const struct got_error *
gw_get_repo_age(char **repo_age, struct gw_trans *gw_trans, char *dir,
const char *refname, int ref_tm)
{
const struct got_error *error = NULL;
struct got_repository *repo = NULL;
struct got_commit_object *commit = NULL;
struct got_reflist_head refs;
struct got_reflist_entry *re;
time_t committer_time = 0, cmp_time = 0;
*repo_age = NULL;
TAILQ_INIT(&refs);
if (gw_trans->gw_conf->got_show_repo_age == 0)
return NULL;
if (gw_trans->repo)
repo = gw_trans->repo;
else {
error = got_repo_open(&repo, dir, NULL);
if (error)
return error;
}
error = got_ref_list(&refs, repo, "refs/heads",
got_ref_cmp_by_name, NULL);
if (error)
goto done;
/*
* Find the youngest branch tip in the repository, or the age of
* the a specific branch tip if a name was provided by the caller.
*/
TAILQ_FOREACH(re, &refs, entry) {
struct got_object_id *id = NULL;
if (refname && strcmp(got_ref_get_name(re->ref), refname) != 0)
continue;
error = got_ref_resolve(&id, repo, re->ref);
if (error)
goto done;
error = got_object_open_as_commit(&commit, repo, id);
free(id);
if (error)
goto done;
committer_time =
got_object_commit_get_committer_time(commit);
got_object_commit_close(commit);
if (cmp_time < committer_time)
cmp_time = committer_time;
if (refname)
break;
}
if (cmp_time != 0) {
committer_time = cmp_time;
error = gw_get_time_str(repo_age, committer_time, ref_tm);
}
done:
got_ref_list_free(&refs);
if (gw_trans->repo == NULL)
got_repo_close(repo);
return error;
}
static const struct got_error *
gw_output_diff(struct gw_trans *gw_trans, struct gw_header *header)
{
const struct got_error *error;
FILE *f = NULL;
struct got_object_id *id1 = NULL, *id2 = NULL;
char *label1 = NULL, *label2 = NULL, *line = NULL;
int obj_type;
size_t linesize = 0;
ssize_t linelen;
enum kcgi_err kerr = KCGI_OK;
f = got_opentemp();
if (f == NULL)
return NULL;
if (header->parent_id != NULL &&
strncmp(header->parent_id, "/dev/null", 9) != 0) {
error = got_repo_match_object_id(&id1, &label1,
header->parent_id, GOT_OBJ_TYPE_ANY,
&header->refs, gw_trans->repo);
if (error)
goto done;
}
error = got_repo_match_object_id(&id2, &label2,
header->commit_id, GOT_OBJ_TYPE_ANY, &header->refs,
gw_trans->repo);
if (error)
goto done;
error = got_object_get_type(&obj_type, gw_trans->repo, id2);
if (error)
goto done;
switch (obj_type) {
case GOT_OBJ_TYPE_BLOB:
error = got_diff_objects_as_blobs(NULL, NULL, id1, id2,
NULL, NULL, 3, 0, 0, gw_trans->repo, f);
break;
case GOT_OBJ_TYPE_TREE:
error = got_diff_objects_as_trees(NULL, NULL, id1, id2,
"", "", 3, 0, 0, gw_trans->repo, f);
break;
case GOT_OBJ_TYPE_COMMIT:
error = got_diff_objects_as_commits(NULL, NULL, id1, id2,
3, 0, 0, gw_trans->repo, f);
break;
default:
error = got_error(GOT_ERR_OBJ_TYPE);
}
if (error)
goto done;
if (fseek(f, 0, SEEK_SET) == -1) {
error = got_ferror(f, GOT_ERR_IO);
goto done;
}
while ((linelen = getline(&line, &linesize, f)) != -1) {
error = gw_colordiff_line(gw_trans, line);
if (error)
goto done;
/* XXX: KHTML_PRETTY breaks this */
kerr = khtml_puts(gw_trans->gw_html_req, line);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
}
if (linelen == -1 && ferror(f))
error = got_error_from_errno("getline");
done:
if (f && fclose(f) == -1 && error == NULL)
error = got_error_from_errno("fclose");
free(line);
free(label1);
free(label2);
free(id1);
free(id2);
if (error == NULL && kerr != KCGI_OK)
error = gw_kcgi_error(kerr);
return error;
}
static const struct got_error *
gw_get_repo_owner(char **owner, struct gw_trans *gw_trans, char *dir)
{
const struct got_error *error = NULL;
struct got_repository *repo;
const char *gitconfig_owner;
*owner = NULL;
if (gw_trans->gw_conf->got_show_repo_owner == 0)
return NULL;
error = got_repo_open(&repo, dir, NULL);
if (error)
return error;
gitconfig_owner = got_repo_get_gitconfig_owner(repo);
if (gitconfig_owner) {
*owner = strdup(gitconfig_owner);
if (*owner == NULL)
error = got_error_from_errno("strdup");
}
got_repo_close(repo);
return error;
}
static const struct got_error *
gw_get_clone_url(char **url, struct gw_trans *gw_trans, char *dir)
{
const struct got_error *error = NULL;
FILE *f;
char *d_file = NULL;
unsigned int len;
size_t n;
*url = NULL;
if (asprintf(&d_file, "%s/cloneurl", dir) == -1)
return got_error_from_errno("asprintf");
f = fopen(d_file, "r");
if (f == NULL) {
if (errno != ENOENT && errno != EACCES)
error = got_error_from_errno2("fopen", d_file);
goto done;
}
if (fseek(f, 0, SEEK_END) == -1) {
error = got_ferror(f, GOT_ERR_IO);
goto done;
}
len = ftell(f);
if (len == -1) {
error = got_ferror(f, GOT_ERR_IO);
goto done;
}
if (fseek(f, 0, SEEK_SET) == -1) {
error = got_ferror(f, GOT_ERR_IO);
goto done;
}
*url = calloc(len + 1, sizeof(**url));
if (*url == NULL) {
error = got_error_from_errno("calloc");
goto done;
}
n = fread(*url, 1, len, f);
if (n == 0 && ferror(f))
error = got_ferror(f, GOT_ERR_IO);
done:
if (f && fclose(f) == -1 && error == NULL)
error = got_error_from_errno("fclose");
free(d_file);
return NULL;
}
static const struct got_error *
gw_output_repo_tags(struct gw_trans *gw_trans, struct gw_header *header,
int limit, int tag_type)
{
const struct got_error *error = NULL;
struct got_reflist_head refs;
struct got_reflist_entry *re;
char *age = NULL;
char *id_str = NULL, *newline, *href_commits = NULL;
char *tag_commit0 = NULL, *href_tag = NULL, *href_briefs = NULL;
struct got_tag_object *tag = NULL;
enum kcgi_err kerr = KCGI_OK;
int summary_header_displayed = 0, start_tag = 0, chk_next = 0;
int prev_set = 0, tag_count = 0;
TAILQ_INIT(&refs);
error = got_ref_list(&refs, gw_trans->repo, "refs/tags",
got_ref_cmp_tags, gw_trans->repo);
if (error)
goto done;
TAILQ_FOREACH(re, &refs, entry) {
const char *refname;
const char *tagger;
const char *tag_commit;
time_t tagger_time;
struct got_object_id *id;
struct got_commit_object *commit = NULL;
refname = got_ref_get_name(re->ref);
if (strncmp(refname, "refs/tags/", 10) != 0)
continue;
refname += 10;
error = got_ref_resolve(&id, gw_trans->repo, re->ref);
if (error)
goto done;
error = got_object_open_as_tag(&tag, gw_trans->repo, id);
if (error) {
if (error->code != GOT_ERR_OBJ_TYPE) {
free(id);
goto done;
}
/* "lightweight" tag */
error = got_object_open_as_commit(&commit,
gw_trans->repo, id);
if (error) {
free(id);
goto done;
}
tagger = got_object_commit_get_committer(commit);
tagger_time =
got_object_commit_get_committer_time(commit);
error = got_object_id_str(&id_str, id);
free(id);
} else {
free(id);
tagger = got_object_tag_get_tagger(tag);
tagger_time = got_object_tag_get_tagger_time(tag);
error = got_object_id_str(&id_str,
got_object_tag_get_object_id(tag));
}
if (error)
goto done;
if (tag_type == TAGFULL && strncmp(id_str, header->commit_id,
strlen(id_str)) != 0)
continue;
if (tag_type == TAGBRIEF && gw_trans->commit_id &&
start_tag == 0 && strncmp(id_str, header->commit_id,
strlen(id_str)) != 0) {
continue;
} else {
start_tag = 1;
}
tag_count++;
if (prev_set == 0 && start_tag == 1) {
gw_trans->next_prev_id = strdup(id_str);
if (gw_trans->next_prev_id == NULL) {
error = got_error_from_errno("strdup");
goto done;
}
prev_set = 1;
}
if (chk_next) {
gw_trans->next_id = strdup(id_str);
if (gw_trans->next_id == NULL)
error = got_error_from_errno("strdup");
goto done;
}
if (commit) {
error = got_object_commit_get_logmsg(&tag_commit0,
commit);
if (error)
goto done;
got_object_commit_close(commit);
} else {
tag_commit0 = strdup(got_object_tag_get_message(tag));
if (tag_commit0 == NULL) {
error = got_error_from_errno("strdup");
goto done;
}
}
tag_commit = tag_commit0;
while (*tag_commit == '\n')
tag_commit++;
switch (tag_type) {
case TAGBRIEF:
newline = strchr(tag_commit, '\n');
if (newline)
*newline = '\0';
if (summary_header_displayed == 0) {
kerr = khtml_attr(gw_trans->gw_html_req,
KELEM_DIV, KATTR_ID,
"summary_tags_title_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req,
KELEM_DIV, KATTR_ID,
"summary_tags_title", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req,
"Tags");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req,
2);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req,
KELEM_DIV, KATTR_ID,
"summary_tags_content", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
summary_header_displayed = 1;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "tag_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "tag_age", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
error = gw_get_time_str(&age, tagger_time, TM_DIFF);
if (error)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req,
age ? age : "");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "tag", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, refname);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "tag_name", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
href_tag = khttp_urlpart(NULL, NULL, "gotweb", "path",
gw_trans->repo_name, "action", "tag", "commit",
id_str, NULL);
if (href_tag == NULL) {
error = got_error_from_errno("khttp_urlpart");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A,
KATTR_HREF, href_tag, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, tag_commit);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 3);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "navs_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "navs", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A,
KATTR_HREF, href_tag, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "tag");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, " | ");
if (kerr != KCGI_OK)
goto done;
href_briefs = khttp_urlpart(NULL, NULL, "gotweb",
"path", gw_trans->repo_name, "action", "briefs",
"commit", id_str, NULL);
if (href_briefs == NULL) {
error = got_error_from_errno("khttp_urlpart");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A,
KATTR_HREF, href_briefs, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req,
"commit briefs");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, " | ");
if (kerr != KCGI_OK)
goto done;
href_commits = khttp_urlpart(NULL, NULL, "gotweb",
"path", gw_trans->repo_name, "action", "commits",
"commit", id_str, NULL);
if (href_commits == NULL) {
error = got_error_from_errno("khttp_urlpart");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A,
KATTR_HREF, href_commits, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "commits");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 3);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "dotted_line", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 2);
if (kerr != KCGI_OK)
goto done;
break;
case TAGFULL:
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "tag_info_date_title", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "Tag Date:");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "tag_info_date", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
error = gw_get_time_str(&age, tagger_time, TM_LONG);
if (error)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req,
age ? age : "");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "tag_info_tagger_title", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "Tagger:");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "tag_info_date", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, tagger);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "tag_info", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khttp_puts(gw_trans->gw_req, tag_commit);
if (kerr != KCGI_OK)
goto done;
break;
default:
break;
}
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
if (limit && --limit == 0)
chk_next = 1;
if (tag)
got_object_tag_close(tag);
tag = NULL;
free(id_str);
id_str = NULL;
free(age);
age = NULL;
free(tag_commit0);
tag_commit0 = NULL;
free(href_tag);
href_tag = NULL;
free(href_briefs);
href_briefs = NULL;
free(href_commits);
href_commits = NULL;
}
if (tag_count == 0) {
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"summary_tags_title_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"summary_tags_title", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "Tags");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 2);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"summary_tags_content", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"tags_info", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khttp_puts(gw_trans->gw_req,
"There are no tags for this repo.");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 2);
}
done:
if (tag)
got_object_tag_close(tag);
free(id_str);
free(age);
free(tag_commit0);
free(href_tag);
free(href_briefs);
free(href_commits);
got_ref_list_free(&refs);
if (error == NULL && kerr != KCGI_OK)
error = gw_kcgi_error(kerr);
return error;
}
static void
gw_free_header(struct gw_header *header)
{
free(header->path);
free(header->author);
free(header->committer);
free(header->refs_str);
free(header->commit_id);
free(header->parent_id);
free(header->tree_id);
free(header->commit_msg);
}
static struct gw_header *
gw_init_header()
{
struct gw_header *header;
header = malloc(sizeof(*header));
if (header == NULL)
return NULL;
header->path = NULL;
TAILQ_INIT(&header->refs);
header->refs_str = NULL;
header->commit_id = NULL;
header->committer = NULL;
header->author = NULL;
header->parent_id = NULL;
header->tree_id = NULL;
header->commit_msg = NULL;
return header;
}
static const struct got_error *
gw_get_commits(struct gw_trans * gw_trans, struct gw_header *header,
int limit, struct got_object_id *id)
{
const struct got_error *error = NULL;
struct got_commit_graph *graph = NULL;
struct got_commit_object *commit = NULL;
int chk_next = 0, chk_multi = 0, prev_set = 0;
error = got_commit_graph_open(&graph, header->path, 0);
if (error)
return error;
error = got_commit_graph_iter_start(graph, id, gw_trans->repo, NULL,
NULL);
if (error)
goto done;
for (;;) {
error = got_commit_graph_iter_next(&id, graph, gw_trans->repo,
NULL, NULL);
if (error) {
if (error->code == GOT_ERR_ITER_COMPLETED)
error = NULL;
goto done;
}
if (id == NULL)
goto done;
error = got_object_open_as_commit(&commit, gw_trans->repo, id);
if (error)
goto done;
if (limit == 1 && chk_multi == 0 &&
gw_trans->gw_conf->got_max_commits_display != 1) {
error = gw_get_commit(gw_trans, header, commit, id);
if (error)
goto done;
} else {
chk_multi = 1;
struct gw_header *n_header = NULL;
if ((n_header = gw_init_header()) == NULL) {
error = got_error_from_errno("malloc");
goto done;
}
error = got_ref_list(&n_header->refs, gw_trans->repo,
NULL, got_ref_cmp_by_name, NULL);
if (error)
goto done;
error = gw_get_commit(gw_trans, n_header, commit, id);
if (error)
goto done;
got_ref_list_free(&n_header->refs);
/*
* we have a commit_id now, so copy it to next_prev_id
* for navigation through gw_briefs and gw_commits
*/
if (gw_trans->next_prev_id == NULL && prev_set == 0 &&
(gw_trans->action == GW_BRIEFS ||
gw_trans->action == GW_COMMITS ||
gw_trans->action == GW_SUMMARY)) {
prev_set = 1;
gw_trans->next_prev_id =
strdup(n_header->commit_id);
if (gw_trans->next_prev_id == NULL) {
error = got_error_from_errno("strdup");
goto done;
}
}
/*
* check for one more commit before breaking,
* so we know whether to navicate through gw_briefs
* gw_commits and gw_summary
*/
if (chk_next && (gw_trans->action == GW_BRIEFS||
gw_trans->action == GW_COMMITS ||
gw_trans->action == GW_SUMMARY)) {
gw_trans->next_id = strdup(n_header->commit_id);
if (gw_trans->next_id == NULL)
error = got_error_from_errno("strdup");
goto done;
}
TAILQ_INSERT_TAIL(&gw_trans->gw_headers, n_header,
entry);
}
if (error || (limit && --limit == 0)) {
if (chk_multi == 0)
break;
chk_next = 1;
}
}
done:
if (commit != NULL)
got_object_commit_close(commit);
if (graph)
got_commit_graph_close(graph);
return error;
}
static const struct got_error *
gw_get_commit(struct gw_trans *gw_trans, struct gw_header *header,
struct got_commit_object *commit, struct got_object_id *id)
{
const struct got_error *error = NULL;
struct got_reflist_entry *re;
struct got_object_id *id2 = NULL;
struct got_object_qid *parent_id;
char *commit_msg = NULL, *commit_msg0;
/*print commit*/
TAILQ_FOREACH(re, &header->refs, entry) {
char *s;
const char *name;
struct got_tag_object *tag = NULL;
struct got_object_id *ref_id;
int cmp;
if (got_ref_is_symbolic(re->ref))
continue;
name = got_ref_get_name(re->ref);
if (strncmp(name, "refs/", 5) == 0)
name += 5;
if (strncmp(name, "got/", 4) == 0)
continue;
if (strncmp(name, "heads/", 6) == 0)
name += 6;
if (strncmp(name, "remotes/", 8) == 0) {
name += 8;
s = strstr(name, "/" GOT_REF_HEAD);
if (s != NULL && s[strlen(s)] == '\0')
continue;
}
error = got_ref_resolve(&ref_id, gw_trans->repo, re->ref);
if (error)
return error;
if (strncmp(name, "tags/", 5) == 0) {
error = got_object_open_as_tag(&tag, gw_trans->repo,
ref_id);
if (error) {
if (error->code != GOT_ERR_OBJ_TYPE) {
free(ref_id);
continue;
}
/*
* Ref points at something other
* than a tag.
*/
error = NULL;
tag = NULL;
}
}
cmp = got_object_id_cmp(tag ?
got_object_tag_get_object_id(tag) : ref_id, id);
free(ref_id);
if (tag)
got_object_tag_close(tag);
if (cmp != 0)
continue;
s = header->refs_str;
if (asprintf(&header->refs_str, "%s%s%s", s ? s : "",
s ? ", " : "", name) == -1) {
error = got_error_from_errno("asprintf");
free(s);
header->refs_str = NULL;
return error;
}
free(s);
}
error = got_object_id_str(&header->commit_id, id);
if (error)
return error;
error = got_object_id_str(&header->tree_id,
got_object_commit_get_tree_id(commit));
if (error)
return error;
if (gw_trans->action == GW_DIFF) {
parent_id = SIMPLEQ_FIRST(
got_object_commit_get_parent_ids(commit));
if (parent_id != NULL) {
id2 = got_object_id_dup(parent_id->id);
free (parent_id);
error = got_object_id_str(&header->parent_id, id2);
if (error)
return error;
free(id2);
} else {
header->parent_id = strdup("/dev/null");
if (header->parent_id == NULL) {
error = got_error_from_errno("strdup");
return error;
}
}
}
header->committer_time =
got_object_commit_get_committer_time(commit);
header->author =
strdup(got_object_commit_get_author(commit));
if (header->author == NULL) {
error = got_error_from_errno("strdup");
return error;
}
header->committer =
strdup(got_object_commit_get_committer(commit));
if (header->committer == NULL) {
error = got_error_from_errno("strdup");
return error;
}
error = got_object_commit_get_logmsg(&commit_msg0, commit);
if (error)
return error;
commit_msg = commit_msg0;
while (*commit_msg == '\n')
commit_msg++;
header->commit_msg = strdup(commit_msg);
if (header->commit_msg == NULL)
error = got_error_from_errno("strdup");
free(commit_msg0);
return error;
}
static const struct got_error *
gw_get_header(struct gw_trans *gw_trans, struct gw_header *header, int limit)
{
const struct got_error *error = NULL;
char *in_repo_path = NULL;
struct got_object_id *id = NULL;
error = got_repo_open(&gw_trans->repo, gw_trans->repo_path, NULL);
if (error)
return error;
if (gw_trans->commit_id == NULL) {
struct got_reference *head_ref;
error = got_ref_open(&head_ref, gw_trans->repo,
gw_trans->headref, 0);
if (error)
return error;
error = got_ref_resolve(&id, gw_trans->repo, head_ref);
got_ref_close(head_ref);
if (error)
return error;
} else {
struct got_reference *ref;
error = got_ref_open(&ref, gw_trans->repo,
gw_trans->commit_id, 0);
if (error == NULL) {
int obj_type;
error = got_ref_resolve(&id, gw_trans->repo, ref);
got_ref_close(ref);
if (error)
return error;
error = got_object_get_type(&obj_type, gw_trans->repo,
id);
if (error)
goto done;
if (obj_type == GOT_OBJ_TYPE_TAG) {
struct got_tag_object *tag;
error = got_object_open_as_tag(&tag,
gw_trans->repo, id);
if (error)
goto done;
if (got_object_tag_get_object_type(tag) !=
GOT_OBJ_TYPE_COMMIT) {
got_object_tag_close(tag);
error = got_error(GOT_ERR_OBJ_TYPE);
goto done;
}
free(id);
id = got_object_id_dup(
got_object_tag_get_object_id(tag));
if (id == NULL)
error = got_error_from_errno(
"got_object_id_dup");
got_object_tag_close(tag);
if (error)
goto done;
} else if (obj_type != GOT_OBJ_TYPE_COMMIT) {
error = got_error(GOT_ERR_OBJ_TYPE);
goto done;
}
}
error = got_repo_match_object_id_prefix(&id,
gw_trans->commit_id, GOT_OBJ_TYPE_COMMIT,
gw_trans->repo);
if (error)
goto done;
}
error = got_repo_map_path(&in_repo_path, gw_trans->repo,
gw_trans->repo_path);
if (error)
goto done;
if (in_repo_path) {
header->path = strdup(in_repo_path);
if (header->path == NULL) {
error = got_error_from_errno("strdup");
goto done;
}
}
error = got_ref_list(&header->refs, gw_trans->repo, NULL,
got_ref_cmp_by_name, NULL);
if (error)
goto done;
error = gw_get_commits(gw_trans, header, limit, id);
done:
got_ref_list_free(&header->refs);
free(id);
free(in_repo_path);
return error;
}
struct blame_line {
int annotated;
char *id_str;
char *committer;
char datebuf[11]; /* YYYY-MM-DD + NUL */
};
struct gw_blame_cb_args {
struct blame_line *lines;
int nlines;
int nlines_prec;
int lineno_cur;
off_t *line_offsets;
FILE *f;
struct got_repository *repo;
struct gw_trans *gw_trans;
};
static const struct got_error *
gw_blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
{
const struct got_error *err = NULL;
struct gw_blame_cb_args *a = arg;
struct blame_line *bline;
char *line = NULL;
size_t linesize = 0;
struct got_commit_object *commit = NULL;
off_t offset;
struct tm tm;
time_t committer_time;
enum kcgi_err kerr = KCGI_OK;
if (nlines != a->nlines ||
(lineno != -1 && lineno < 1) || lineno > a->nlines)
return got_error(GOT_ERR_RANGE);
if (lineno == -1)
return NULL; /* no change in this commit */
/* Annotate this line. */
bline = &a->lines[lineno - 1];
if (bline->annotated)
return NULL;
err = got_object_id_str(&bline->id_str, id);
if (err)
return err;
err = got_object_open_as_commit(&commit, a->repo, id);
if (err)
goto done;
bline->committer = strdup(got_object_commit_get_committer(commit));
if (bline->committer == NULL) {
err = got_error_from_errno("strdup");
goto done;
}
committer_time = got_object_commit_get_committer_time(commit);
if (localtime_r(&committer_time, &tm) == NULL)
return got_error_from_errno("localtime_r");
if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
&tm) >= sizeof(bline->datebuf)) {
err = got_error(GOT_ERR_NO_SPACE);
goto done;
}
bline->annotated = 1;
/* Print lines annotated so far. */
bline = &a->lines[a->lineno_cur - 1];
if (!bline->annotated)
goto done;
offset = a->line_offsets[a->lineno_cur - 1];
if (fseeko(a->f, offset, SEEK_SET) == -1) {
err = got_error_from_errno("fseeko");
goto done;
}
while (bline->annotated) {
char *smallerthan, *at, *nl, *committer;
char *href_diff = NULL;
size_t len;
if (getline(&line, &linesize, a->f) == -1) {
if (ferror(a->f))
err = got_error_from_errno("getline");
break;
}
committer = bline->committer;
smallerthan = strchr(committer, '<');
if (smallerthan && smallerthan[1] != '\0')
committer = smallerthan + 1;
at = strchr(committer, '@');
if (at)
*at = '\0';
len = strlen(committer);
if (len >= 9)
committer[8] = '\0';
nl = strchr(line, '\n');
if (nl)
*nl = '\0';
kerr = khtml_attr(a->gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"blame_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
goto err;
kerr = khtml_attr(a->gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"blame_number", KATTR__MAX);
if (kerr != KCGI_OK)
goto err;
kerr = khtml_printf(a->gw_trans->gw_html_req, "%.*d",
a->nlines_prec, a->lineno_cur);
if (kerr != KCGI_OK)
goto err;
kerr = khtml_closeelem(a->gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto err;
kerr = khtml_attr(a->gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"blame_hash", KATTR__MAX);
if (kerr != KCGI_OK)
goto err;
href_diff = khttp_urlpart(NULL, NULL, "gotweb", "path",
a->gw_trans->repo_name, "action", "diff", "commit",
bline->id_str, NULL);
if (href_diff == NULL) {
err = got_error_from_errno("khttp_urlpart");
goto done;
}
kerr = khtml_attr(a->gw_trans->gw_html_req, KELEM_A,
KATTR_HREF, href_diff, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_printf(a->gw_trans->gw_html_req, "%.8s",
bline->id_str);
if (kerr != KCGI_OK)
goto err;
kerr = khtml_closeelem(a->gw_trans->gw_html_req, 2);
if (kerr != KCGI_OK)
goto err;
kerr = khtml_attr(a->gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"blame_date", KATTR__MAX);
if (kerr != KCGI_OK)
goto err;
kerr = khtml_puts(a->gw_trans->gw_html_req, bline->datebuf);
if (kerr != KCGI_OK)
goto err;
kerr = khtml_closeelem(a->gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto err;
kerr = khtml_attr(a->gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"blame_author", KATTR__MAX);
if (kerr != KCGI_OK)
goto err;
kerr = khtml_puts(a->gw_trans->gw_html_req, committer);
if (kerr != KCGI_OK)
goto err;
kerr = khtml_closeelem(a->gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto err;
kerr = khtml_attr(a->gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"blame_code", KATTR__MAX);
if (kerr != KCGI_OK)
goto err;
kerr = khtml_puts(a->gw_trans->gw_html_req, line);
if (kerr != KCGI_OK)
goto err;
kerr = khtml_closeelem(a->gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto err;
kerr = khtml_closeelem(a->gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto err;
a->lineno_cur++;
bline = &a->lines[a->lineno_cur - 1];
err:
free(href_diff);
}
done:
if (commit)
got_object_commit_close(commit);
free(line);
if (err == NULL && kerr != KCGI_OK)
err = gw_kcgi_error(kerr);
return err;
}
static const struct got_error *
gw_output_file_blame(struct gw_trans *gw_trans, struct gw_header *header)
{
const struct got_error *error = NULL;
struct got_object_id *obj_id = NULL;
struct got_object_id *commit_id = NULL;
struct got_blob_object *blob = NULL;
char *path = NULL, *in_repo_path = NULL;
struct gw_blame_cb_args bca;
int i, obj_type;
off_t filesize;
if (asprintf(&path, "%s%s%s",
gw_trans->repo_folder ? gw_trans->repo_folder : "",
gw_trans->repo_folder ? "/" : "",
gw_trans->repo_file) == -1) {
error = got_error_from_errno("asprintf");
goto done;
}
error = got_repo_map_path(&in_repo_path, gw_trans->repo, path);
if (error)
goto done;
error = got_repo_match_object_id(&commit_id, NULL, gw_trans->commit_id,
GOT_OBJ_TYPE_COMMIT, &header->refs, gw_trans->repo);
if (error)
goto done;
error = got_object_id_by_path(&obj_id, gw_trans->repo, commit_id,
in_repo_path);
if (error)
goto done;
if (obj_id == NULL) {
error = got_error(GOT_ERR_NO_OBJ);
goto done;
}
error = got_object_get_type(&obj_type, gw_trans->repo, obj_id);
if (error)
goto done;
if (obj_type != GOT_OBJ_TYPE_BLOB) {
error = got_error(GOT_ERR_OBJ_TYPE);
goto done;
}
error = got_object_open_as_blob(&blob, gw_trans->repo, obj_id, 8192);
if (error)
goto done;
bca.f = got_opentemp();
if (bca.f == NULL) {
error = got_error_from_errno("got_opentemp");
goto done;
}
error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
&bca.line_offsets, bca.f, blob);
if (error || bca.nlines == 0)
goto done;
/* Don't include \n at EOF in the blame line count. */
if (bca.line_offsets[bca.nlines - 1] == filesize)
bca.nlines--;
bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
if (bca.lines == NULL) {
error = got_error_from_errno("calloc");
goto done;
}
bca.lineno_cur = 1;
bca.nlines_prec = 0;
i = bca.nlines;
while (i > 0) {
i /= 10;
bca.nlines_prec++;
}
bca.repo = gw_trans->repo;
bca.gw_trans = gw_trans;
error = got_blame(in_repo_path, commit_id, gw_trans->repo, gw_blame_cb,
&bca, NULL, NULL);
done:
free(in_repo_path);
free(commit_id);
free(obj_id);
free(path);
if (blob) {
free(bca.line_offsets);
for (i = 0; i < bca.nlines; i++) {
struct blame_line *bline = &bca.lines[i];
free(bline->id_str);
free(bline->committer);
}
free(bca.lines);
if (bca.f && fclose(bca.f) == EOF && error == NULL)
error = got_error_from_errno("fclose");
}
if (blob)
got_object_blob_close(blob);
return error;
}
static const struct got_error *
gw_output_blob_buf(struct gw_trans *gw_trans, struct gw_header *header)
{
const struct got_error *error = NULL;
struct got_object_id *obj_id = NULL;
struct got_object_id *commit_id = NULL;
struct got_blob_object *blob = NULL;
char *path = NULL, *in_repo_path = NULL;
int obj_type, set_mime = 0;
size_t len, hdrlen;
const uint8_t *buf;
enum kcgi_err kerr = KCGI_OK;
if (asprintf(&path, "%s%s%s",
gw_trans->repo_folder ? gw_trans->repo_folder : "",
gw_trans->repo_folder ? "/" : "",
gw_trans->repo_file) == -1) {
error = got_error_from_errno("asprintf");
goto done;
}
error = got_repo_map_path(&in_repo_path, gw_trans->repo, path);
if (error)
goto done;
error = got_repo_match_object_id(&commit_id, NULL, gw_trans->commit_id,
GOT_OBJ_TYPE_COMMIT, &header->refs, gw_trans->repo);
if (error)
goto done;
error = got_object_id_by_path(&obj_id, gw_trans->repo, commit_id,
in_repo_path);
if (error)
goto done;
if (obj_id == NULL) {
error = got_error(GOT_ERR_NO_OBJ);
goto done;
}
error = got_object_get_type(&obj_type, gw_trans->repo, obj_id);
if (error)
goto done;
if (obj_type != GOT_OBJ_TYPE_BLOB) {
error = got_error(GOT_ERR_OBJ_TYPE);
goto done;
}
error = got_object_open_as_blob(&blob, gw_trans->repo, obj_id, 8192);
if (error)
goto done;
hdrlen = got_object_blob_get_hdrlen(blob);
do {
error = got_object_blob_read_block(&len, blob);
if (error)
goto done;
buf = got_object_blob_get_read_buf(blob);
/*
* Skip blob object header first time around,
* which also contains a zero byte.
*/
buf += hdrlen;
if (set_mime == 0) {
if (isbinary(buf, len - hdrlen))
gw_trans->mime = KMIME_APP_OCTET_STREAM;
else
gw_trans->mime = KMIME_TEXT_PLAIN;
set_mime = 1;
error = gw_display_index(gw_trans);
if (error)
goto done;
}
kerr = khttp_write(gw_trans->gw_req, buf, len - hdrlen);
if (kerr != KCGI_OK)
goto done;
hdrlen = 0;
} while (len != 0);
done:
free(in_repo_path);
free(commit_id);
free(obj_id);
free(path);
if (blob)
got_object_blob_close(blob);
if (error == NULL && kerr != KCGI_OK)
error = gw_kcgi_error(kerr);
return error;
}
static const struct got_error *
gw_output_repo_tree(struct gw_trans *gw_trans, struct gw_header *header)
{
const struct got_error *error = NULL;
struct got_object_id *tree_id = NULL, *commit_id = NULL;
struct got_tree_object *tree = NULL;
char *path = NULL, *in_repo_path = NULL;
char *id_str = NULL;
char *build_folder = NULL;
char *href_blob = NULL, *href_blame = NULL;
const char *class = NULL;
int nentries, i, class_flip = 0;
enum kcgi_err kerr = KCGI_OK;
if (gw_trans->repo_folder != NULL) {
path = strdup(gw_trans->repo_folder);
if (path == NULL) {
error = got_error_from_errno("strdup");
goto done;
}
} else {
error = got_repo_map_path(&in_repo_path, gw_trans->repo,
gw_trans->repo_path);
if (error)
goto done;
free(path);
path = in_repo_path;
}
if (gw_trans->commit_id == NULL) {
struct got_reference *head_ref;
error = got_ref_open(&head_ref, gw_trans->repo,
gw_trans->headref, 0);
if (error)
goto done;
error = got_ref_resolve(&commit_id, gw_trans->repo, head_ref);
if (error)
goto done;
got_ref_close(head_ref);
/*
* gw_trans->commit_id was not parsed from the querystring
* we hit this code path from gw_index, where we don't know the
* commit values for the tree link yet, so set
* gw_trans->commit_id here to continue further into the tree
*/
error = got_object_id_str(&gw_trans->commit_id, commit_id);
if (error)
goto done;
} else {
error = got_repo_match_object_id(&commit_id, NULL,
gw_trans->commit_id, GOT_OBJ_TYPE_COMMIT, &header->refs,
gw_trans->repo);
if (error)
goto done;
}
error = got_object_id_by_path(&tree_id, gw_trans->repo, commit_id,
path);
if (error)
goto done;
error = got_object_open_as_tree(&tree, gw_trans->repo, tree_id);
if (error)
goto done;
nentries = got_object_tree_get_nentries(tree);
for (i = 0; i < nentries; i++) {
struct got_tree_entry *te;
const char *modestr = "";
mode_t mode;
te = got_object_tree_get_entry(tree, i);
error = got_object_id_str(&id_str, got_tree_entry_get_id(te));
if (error)
goto done;
mode = got_tree_entry_get_mode(te);
if (got_object_tree_entry_is_submodule(te))
modestr = "$";
else if (S_ISLNK(mode))
modestr = "@";
else if (S_ISDIR(mode))
modestr = "/";
else if (mode & S_IXUSR)
modestr = "*";
if (class_flip == 0) {
class = "back_lightgray";
class_flip = 1;
} else {
class = "back_white";
class_flip = 0;
}
if (S_ISDIR(mode)) {
if (asprintf(&build_folder, "%s/%s",
gw_trans->repo_folder ? gw_trans->repo_folder : "",
got_tree_entry_get_name(te)) == -1) {
error = got_error_from_errno("asprintf");
goto done;
}
href_blob = khttp_urlpart(NULL, NULL, "gotweb", "path",
gw_trans->repo_name, "action",
gw_get_action_name(gw_trans), "commit",
gw_trans->commit_id, "folder", build_folder, NULL);
if (href_blob == NULL) {
error = got_error_from_errno("khttp_urlpart");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "tree_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "tree_line", KATTR_CLASS, class,
KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A,
KATTR_HREF, href_blob, KATTR_CLASS,
"diff_directory", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_printf(gw_trans->gw_html_req, "%s%s",
got_tree_entry_get_name(te), modestr);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 2);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "tree_line_blank", KATTR_CLASS, class,
KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_entity(gw_trans->gw_html_req,
KENTITY_nbsp);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 2);
if (kerr != KCGI_OK)
goto done;
} else {
href_blob = khttp_urlpart(NULL, NULL, "gotweb", "path",
gw_trans->repo_name, "action", "blob", "commit",
gw_trans->commit_id, "file",
got_tree_entry_get_name(te), "folder",
gw_trans->repo_folder ? gw_trans->repo_folder : "",
NULL);
if (href_blob == NULL) {
error = got_error_from_errno("khttp_urlpart");
goto done;
}
href_blame = khttp_urlpart(NULL, NULL, "gotweb", "path",
gw_trans->repo_name, "action", "blame", "commit",
gw_trans->commit_id, "file",
got_tree_entry_get_name(te), "folder",
gw_trans->repo_folder ? gw_trans->repo_folder : "",
NULL);
if (href_blame == NULL) {
error = got_error_from_errno("khttp_urlpart");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "tree_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "tree_line", KATTR_CLASS, class,
KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A,
KATTR_HREF, href_blob, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_printf(gw_trans->gw_html_req, "%s%s",
got_tree_entry_get_name(te), modestr);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 2);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "tree_line_navs", KATTR_CLASS, class,
KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A,
KATTR_HREF, href_blob, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "blob");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, " | ");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A,
KATTR_HREF, href_blame, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "blame");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 3);
if (kerr != KCGI_OK)
goto done;
}
free(id_str);
id_str = NULL;
free(href_blob);
href_blob = NULL;
free(build_folder);
build_folder = NULL;
}
done:
if (tree)
got_object_tree_close(tree);
free(id_str);
free(href_blob);
free(href_blame);
free(in_repo_path);
free(tree_id);
free(build_folder);
if (error == NULL && kerr != KCGI_OK)
error = gw_kcgi_error(kerr);
return error;
}
static const struct got_error *
gw_output_repo_heads(struct gw_trans *gw_trans)
{
const struct got_error *error = NULL;
struct got_reflist_head refs;
struct got_reflist_entry *re;
char *age = NULL, *href_summary = NULL, *href_briefs = NULL;
char *href_commits = NULL;
enum kcgi_err kerr = KCGI_OK;
TAILQ_INIT(&refs);
error = got_ref_list(&refs, gw_trans->repo, "refs/heads",
got_ref_cmp_by_name, NULL);
if (error)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "summary_heads_title_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "summary_heads_title", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "Heads");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 2);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "summary_heads_content", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
TAILQ_FOREACH(re, &refs, entry) {
const char *refname;
if (got_ref_is_symbolic(re->ref))
continue;
refname = got_ref_get_name(re->ref);
if (strncmp(refname, "refs/heads/", 11) != 0)
continue;
error = gw_get_repo_age(&age, gw_trans, gw_trans->gw_dir->path,
refname, TM_DIFF);
if (error)
goto done;
if (strncmp(refname, "refs/heads/", 11) == 0)
refname += 11;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "heads_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "heads_age", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, age ? age : "");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "heads_space", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_entity(gw_trans->gw_html_req, KENTITY_nbsp);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV,
KATTR_ID, "head", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
href_summary = khttp_urlpart(NULL, NULL, "gotweb", "path",
gw_trans->repo_name, "action", "summary", "headref",
refname, NULL);
if (href_summary == NULL) {
error = got_error_from_errno("khttp_urlpart");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A, KATTR_HREF,
href_summary, KATTR__MAX);
kerr = khtml_puts(gw_trans->gw_html_req, refname);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 3);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"navs_wrapper", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"navs", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A, KATTR_HREF,
href_summary, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "summary");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, " | ");
if (kerr != KCGI_OK)
goto done;
href_briefs = khttp_urlpart(NULL, NULL, "gotweb", "path",
gw_trans->repo_name, "action", "briefs", "headref",
refname, NULL);
if (href_briefs == NULL) {
error = got_error_from_errno("khttp_urlpart");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A, KATTR_HREF,
href_briefs, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "commit briefs");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, " | ");
if (kerr != KCGI_OK)
goto done;
href_commits = khttp_urlpart(NULL, NULL, "gotweb", "path",
gw_trans->repo_name, "action", "commits", "headref",
refname, NULL);
if (href_commits == NULL) {
error = got_error_from_errno("khttp_urlpart");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A, KATTR_HREF,
href_commits, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, "commits");
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 3);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"dotted_line", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 2);
if (kerr != KCGI_OK)
goto done;
free(href_summary);
href_summary = NULL;
free(href_briefs);
href_briefs = NULL;
free(href_commits);
href_commits = NULL;
}
done:
got_ref_list_free(&refs);
free(href_summary);
free(href_briefs);
free(href_commits);
return error;
}
static const struct got_error *
gw_output_site_link(struct gw_trans *gw_trans)
{
const struct got_error *error = NULL;
char *href_summary = NULL;
enum kcgi_err kerr = KCGI_OK;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"site_link", KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A, KATTR_HREF, GOTWEB,
KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req,
gw_trans->gw_conf->got_site_link);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
if (gw_trans->repo_name != NULL) {
kerr = khtml_puts(gw_trans->gw_html_req, " / ");
if (kerr != KCGI_OK)
goto done;
href_summary = khttp_urlpart(NULL, NULL, "gotweb", "path",
gw_trans->repo_name, "action", "summary", NULL);
if (href_summary == NULL) {
error = got_error_from_errno("khttp_urlpart");
goto done;
}
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_A, KATTR_HREF,
href_summary, KATTR__MAX);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_puts(gw_trans->gw_html_req, gw_trans->repo_name);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
kerr = khtml_printf(gw_trans->gw_html_req, " / %s",
gw_get_action_name(gw_trans));
if (kerr != KCGI_OK)
goto done;
}
kerr = khtml_closeelem(gw_trans->gw_html_req, 1);
if (kerr != KCGI_OK)
goto done;
done:
free(href_summary);
if (error == NULL && kerr != KCGI_OK)
error = gw_kcgi_error(kerr);
return error;
}
static const struct got_error *
gw_colordiff_line(struct gw_trans *gw_trans, char *buf)
{
const struct got_error *error = NULL;
char *color = NULL;
enum kcgi_err kerr = KCGI_OK;
if (strncmp(buf, "-", 1) == 0)
color = "diff_minus";
else if (strncmp(buf, "+", 1) == 0)
color = "diff_plus";
else if (strncmp(buf, "@@", 2) == 0)
color = "diff_chunk_header";
else if (strncmp(buf, "@@", 2) == 0)
color = "diff_chunk_header";
else if (strncmp(buf, "commit +", 8) == 0)
color = "diff_meta";
else if (strncmp(buf, "commit -", 8) == 0)
color = "diff_meta";
else if (strncmp(buf, "blob +", 6) == 0)
color = "diff_meta";
else if (strncmp(buf, "blob -", 6) == 0)
color = "diff_meta";
else if (strncmp(buf, "file +", 6) == 0)
color = "diff_meta";
else if (strncmp(buf, "file -", 6) == 0)
color = "diff_meta";
else if (strncmp(buf, "from:", 5) == 0)
color = "diff_author";
else if (strncmp(buf, "via:", 4) == 0)
color = "diff_author";
else if (strncmp(buf, "date:", 5) == 0)
color = "diff_date";
kerr = khtml_attr(gw_trans->gw_html_req, KELEM_DIV, KATTR_ID,
"diff_line", KATTR_CLASS, color ? color : "", KATTR__MAX);
if (error == NULL && kerr != KCGI_OK)
error = gw_kcgi_error(kerr);
return error;
}
int
main(int argc, char *argv[])
{
const struct got_error *error = NULL;
struct gw_trans *gw_trans;
struct gw_dir *dir = NULL, *tdir;
const char *page = "index";
enum kcgi_err kerr = KCGI_OK;
if ((gw_trans = malloc(sizeof(struct gw_trans))) == NULL)
errx(1, "malloc");
if ((gw_trans->gw_req = malloc(sizeof(struct kreq))) == NULL)
errx(1, "malloc");
if ((gw_trans->gw_html_req = malloc(sizeof(struct khtmlreq))) == NULL)
errx(1, "malloc");
if ((gw_trans->gw_tmpl = malloc(sizeof(struct ktemplate))) == NULL)
errx(1, "malloc");
kerr = khttp_parse(gw_trans->gw_req, gw_keys, KEY__ZMAX, &page, 1, 0);
if (kerr != KCGI_OK) {
error = gw_kcgi_error(kerr);
goto done;
}
TAILQ_INIT(&gw_trans->gw_dirs);
TAILQ_INIT(&gw_trans->gw_headers);
gw_trans->action = -1;
gw_trans->page = 0;
gw_trans->repos_total = 0;
gw_trans->repo_path = NULL;
gw_trans->commit_id = NULL;
gw_trans->next_id = NULL;
gw_trans->next_prev_id = NULL;
gw_trans->prev_id = NULL;
gw_trans->prev_prev_id = NULL;
gw_trans->headref = GOT_REF_HEAD;
gw_trans->mime = KMIME_TEXT_HTML;
gw_trans->gw_tmpl->key = gw_templs;
gw_trans->gw_tmpl->keysz = TEMPL__MAX;
gw_trans->gw_tmpl->arg = gw_trans;
gw_trans->gw_tmpl->cb = gw_template;
error = parse_gotweb_config(&gw_trans->gw_conf, GOTWEB_CONF);
if (error)
goto done;
error = gw_parse_querystring(gw_trans);
if (error)
goto done;
if (gw_trans->action == GW_BLOB)
error = gw_blob(gw_trans);
else
error = gw_display_index(gw_trans);
done:
free(gw_trans->gw_conf->got_repos_path);
free(gw_trans->gw_conf->got_www_path);
free(gw_trans->gw_conf->got_site_name);
free(gw_trans->gw_conf->got_site_owner);
free(gw_trans->gw_conf->got_site_link);
free(gw_trans->gw_conf->got_logo);
free(gw_trans->gw_conf->got_logo_url);
free(gw_trans->gw_conf);
free(gw_trans->commit_id);
free(gw_trans->next_id);
free(gw_trans->next_prev_id);
free(gw_trans->prev_id);
free(gw_trans->prev_prev_id);
free(gw_trans->repo_path);
if (gw_trans->repo)
got_repo_close(gw_trans->repo);
TAILQ_FOREACH_SAFE(dir, &gw_trans->gw_dirs, entry, tdir) {
free(dir->name);
free(dir->description);
free(dir->age);
free(dir->url);
free(dir->path);
free(dir);
}
khttp_free(gw_trans->gw_req);
return 0;
}
|
ThomasAdam/gameoftrees
|
lib/delta.c
|
<gh_stars>1-10
/*
* Copyright (c) 2018 <NAME> <<EMAIL>>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <limits.h>
#include <zlib.h>
#include <sha1.h>
#include <time.h>
#include <zlib.h>
#include "got_error.h"
#include "got_repository.h"
#include "got_object.h"
#include "got_path.h"
#include "got_lib_delta.h"
#include "got_lib_inflate.h"
#include "got_lib_object.h"
#ifndef MIN
#define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
#endif
struct got_delta *
got_delta_open(off_t offset, size_t tslen, int type, size_t size,
off_t data_offset)
{
struct got_delta *delta;
delta = malloc(sizeof(*delta));
if (delta == NULL)
return NULL;
delta->type = type;
delta->offset = offset;
delta->tslen = tslen;
delta->size = size;
delta->data_offset = data_offset;
return delta;
}
const struct got_error *
got_delta_chain_get_base_type(int *type, struct got_delta_chain *deltas)
{
struct got_delta *delta;
/* The first delta in the chain should represent the base object. */
delta = SIMPLEQ_FIRST(&deltas->entries);
if (delta->type == GOT_OBJ_TYPE_COMMIT ||
delta->type == GOT_OBJ_TYPE_TREE ||
delta->type == GOT_OBJ_TYPE_BLOB ||
delta->type == GOT_OBJ_TYPE_TAG) {
*type = delta->type;
return NULL;
}
return got_error(GOT_ERR_BAD_DELTA_CHAIN);
}
/* Fetch another (required) byte from the delta stream. */
static const struct got_error *
next_delta_byte(const uint8_t **p, size_t *remain)
{
if (--(*remain) == 0)
return got_error(GOT_ERR_BAD_DELTA);
(*p)++;
return NULL;
}
static const struct got_error *
parse_size(uint64_t *size, const uint8_t **p, size_t *remain)
{
const struct got_error *err = NULL;
int i = 0;
*size = 0;
do {
/* We do not support size values which don't fit in 64 bit. */
if (i > 9)
return got_error(GOT_ERR_NO_SPACE);
if (i == 0)
*size = ((**p) & GOT_DELTA_SIZE_VAL_MASK);
else {
size_t shift = GOT_DELTA_SIZE_SHIFT * i;
*size |= (((**p) & GOT_DELTA_SIZE_VAL_MASK) << shift);
}
if (((**p) & GOT_DELTA_SIZE_MORE) == 0)
break;
i++;
err = next_delta_byte(p, remain);
} while (err == NULL);
return err;
}
static const struct got_error *
parse_opcode(off_t *offset, size_t *len, const uint8_t **p, size_t *remain)
{
const struct got_error *err = NULL;
off_t o = 0;
size_t l = 0;
uint8_t opcode = **p;
if (opcode & GOT_DELTA_COPY_OFF1) {
err = next_delta_byte(p, remain);
if (err)
return err;
o = (off_t)(**p);
}
if (opcode & GOT_DELTA_COPY_OFF2) {
err = next_delta_byte(p, remain);
if (err)
return err;
o |= ((off_t)(**p)) << 8;
}
if (opcode & GOT_DELTA_COPY_OFF3) {
err = next_delta_byte(p, remain);
if (err)
return err;
o |= ((off_t)(**p)) << 16;
}
if (opcode & GOT_DELTA_COPY_OFF4) {
err = next_delta_byte(p, remain);
if (err)
return err;
o |= ((off_t)(**p)) << 24;
}
if (opcode & GOT_DELTA_COPY_LEN1) {
err = next_delta_byte(p, remain);
if (err)
return err;
l = (off_t)(**p);
}
if (opcode & GOT_DELTA_COPY_LEN2) {
err = next_delta_byte(p, remain);
if (err)
return err;
l |= ((off_t)(**p)) << 8;
}
if (opcode & GOT_DELTA_COPY_LEN3) {
err = next_delta_byte(p, remain);
if (err)
return err;
l |= ((off_t)(**p)) << 16;
}
if (o == 0)
o = GOT_DELTA_COPY_DEFAULT_OFF;
if (l == 0)
l = GOT_DELTA_COPY_DEFAULT_LEN;
*offset = o;
*len = l;
return NULL;
}
static const struct got_error *
copy_from_base(FILE *base_file, off_t offset, size_t size, FILE *outfile)
{
if (fseeko(base_file, offset, SEEK_SET) != 0)
return got_error_from_errno("fseeko");
while (size > 0) {
uint8_t data[2048];
size_t len = MIN(size, sizeof(data));
size_t n;
n = fread(data, len, 1, base_file);
if (n != 1)
return got_ferror(base_file, GOT_ERR_IO);
n = fwrite(data, len, 1, outfile);
if (n != 1)
return got_ferror(outfile, GOT_ERR_IO);
size -= len;
}
return NULL;
}
static const struct got_error *
copy_from_delta(const uint8_t **p, size_t *remain, size_t len, FILE *outfile)
{
size_t n;
if (*remain < len)
return got_error(GOT_ERR_BAD_DELTA);
n = fwrite(*p, len, 1, outfile);
if (n != 1)
return got_ferror(outfile, GOT_ERR_IO);
*p += len;
*remain -= len;
return NULL;
}
static const struct got_error *
parse_delta_sizes(uint64_t *base_size, uint64_t *result_size,
const uint8_t **p, size_t *remain)
{
const struct got_error *err;
/* Read the two size fields at the beginning of the stream. */
err = parse_size(base_size, p, remain);
if (err)
return err;
err = next_delta_byte(p, remain);
if (err)
return err;
err = parse_size(result_size, p, remain);
if (err)
return err;
return NULL;
}
const struct got_error *
got_delta_get_sizes(uint64_t *base_size, uint64_t *result_size,
const uint8_t *delta_buf, size_t delta_len)
{
size_t remain;
const uint8_t *p;
if (delta_len < GOT_DELTA_STREAM_LENGTH_MIN)
return got_error(GOT_ERR_BAD_DELTA);
p = delta_buf;
remain = delta_len;
return parse_delta_sizes(base_size, result_size, &p, &remain);
}
const struct got_error *
got_delta_apply_in_mem(uint8_t *base_buf, size_t base_bufsz,
const uint8_t *delta_buf, size_t delta_len, uint8_t *outbuf,
size_t *outsize, size_t maxoutsize)
{
const struct got_error *err = NULL;
uint64_t base_size, result_size;
size_t remain;
const uint8_t *p;
*outsize= 0;
if (delta_len < GOT_DELTA_STREAM_LENGTH_MIN)
return got_error(GOT_ERR_BAD_DELTA);
p = delta_buf;
remain = delta_len;
err = parse_delta_sizes(&base_size, &result_size, &p, &remain);
if (err)
return err;
/* Decode and execute copy instructions from the delta stream. */
err = next_delta_byte(&p, &remain);
while (err == NULL && remain > 0) {
if (*p & GOT_DELTA_BASE_COPY) {
off_t offset = 0;
size_t len = 0;
err = parse_opcode(&offset, &len, &p, &remain);
if (err)
break;
if (SIZE_MAX - offset < len || offset + len < 0 ||
base_bufsz < offset + len ||
*outsize + len > maxoutsize)
return got_error(GOT_ERR_BAD_DELTA);
memcpy(outbuf + *outsize, base_buf + offset, len);
if (err == NULL) {
*outsize += len;
if (remain > 0) {
p++;
remain--;
}
}
} else {
size_t len = (size_t)*p;
if (len == 0) {
err = got_error(GOT_ERR_BAD_DELTA);
break;
}
err = next_delta_byte(&p, &remain);
if (err)
break;
if (remain < len || SIZE_MAX - *outsize < len ||
*outsize + len > maxoutsize)
return got_error(GOT_ERR_BAD_DELTA);
memcpy(outbuf + *outsize, p, len);
p += len;
remain -= len;
*outsize += len;
}
}
if (*outsize != result_size)
err = got_error(GOT_ERR_BAD_DELTA);
return err;
}
const struct got_error *
got_delta_apply(FILE *base_file, const uint8_t *delta_buf,
size_t delta_len, FILE *outfile, size_t *outsize)
{
const struct got_error *err = NULL;
uint64_t base_size, result_size;
size_t remain = 0;
const uint8_t *p;
FILE *memstream = NULL;
char *memstream_buf = NULL;
size_t memstream_size = 0;
*outsize = 0;
if (delta_len < GOT_DELTA_STREAM_LENGTH_MIN)
return got_error(GOT_ERR_BAD_DELTA);
p = delta_buf;
remain = delta_len;
err = parse_delta_sizes(&base_size, &result_size, &p, &remain);
if (err)
return err;
if (result_size < GOT_DELTA_RESULT_SIZE_CACHED_MAX)
memstream = open_memstream(&memstream_buf, &memstream_size);
/* Decode and execute copy instructions from the delta stream. */
err = next_delta_byte(&p, &remain);
while (err == NULL && remain > 0) {
if (*p & GOT_DELTA_BASE_COPY) {
off_t offset = 0;
size_t len = 0;
err = parse_opcode(&offset, &len, &p, &remain);
if (err)
break;
err = copy_from_base(base_file, offset, len,
memstream ? memstream : outfile);
if (err == NULL) {
*outsize += len;
if (remain > 0) {
p++;
remain--;
}
}
} else {
size_t len = (size_t)*p;
if (len == 0) {
err = got_error(GOT_ERR_BAD_DELTA);
break;
}
err = next_delta_byte(&p, &remain);
if (err)
break;
err = copy_from_delta(&p, &remain, len,
memstream ? memstream : outfile);
if (err == NULL)
*outsize += len;
}
}
if (*outsize != result_size)
err = got_error(GOT_ERR_BAD_DELTA);
if (memstream != NULL) {
if (fclose(memstream) != 0)
err = got_error_from_errno("fclose");
if (err == NULL) {
size_t n;
n = fwrite(memstream_buf, 1, memstream_size, outfile);
if (n != memstream_size)
err = got_ferror(outfile, GOT_ERR_IO);
}
free(memstream_buf);
}
if (err == NULL)
rewind(outfile);
return err;
}
|
ThomasAdam/gameoftrees
|
lib/deflate.c
|
<reponame>ThomasAdam/gameoftrees
/*
* Copyright (c) 2019 <NAME> <<EMAIL>>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sha1.h>
#include <zlib.h>
#include <time.h>
#include "got_error.h"
#include "got_object.h"
#include "got_path.h"
#include "got_lib_deflate.h"
#ifndef MIN
#define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
#endif
const struct got_error *
got_deflate_init(struct got_deflate_buf *zb, uint8_t *outbuf, size_t bufsize)
{
const struct got_error *err = NULL;
int zerr;
memset(&zb->z, 0, sizeof(zb->z));
zb->z.zalloc = Z_NULL;
zb->z.zfree = Z_NULL;
zerr = deflateInit(&zb->z, Z_DEFAULT_COMPRESSION);
if (zerr != Z_OK) {
if (zerr == Z_ERRNO)
return got_error_from_errno("deflateInit");
if (zerr == Z_MEM_ERROR) {
errno = ENOMEM;
return got_error_from_errno("deflateInit");
}
return got_error(GOT_ERR_COMPRESSION);
}
zb->inlen = zb->outlen = bufsize;
zb->inbuf = calloc(1, zb->inlen);
if (zb->inbuf == NULL) {
err = got_error_from_errno("calloc");
goto done;
}
zb->flags = 0;
if (outbuf == NULL) {
zb->outbuf = calloc(1, zb->outlen);
if (zb->outbuf == NULL) {
err = got_error_from_errno("calloc");
goto done;
}
zb->flags |= GOT_DEFLATE_F_OWN_OUTBUF;
} else
zb->outbuf = outbuf;
done:
if (err)
got_deflate_end(zb);
return err;
}
const struct got_error *
got_deflate_read(struct got_deflate_buf *zb, FILE *f, size_t *outlenp)
{
size_t last_total_out = zb->z.total_out;
z_stream *z = &zb->z;
int ret = Z_ERRNO;
z->next_out = zb->outbuf;
z->avail_out = zb->outlen;
*outlenp = 0;
do {
if (z->avail_in == 0) {
size_t n = fread(zb->inbuf, 1, zb->inlen, f);
if (n == 0) {
if (ferror(f))
return got_ferror(f, GOT_ERR_IO);
/* EOF */
ret = deflate(z, Z_FINISH);
break;
}
z->next_in = zb->inbuf;
z->avail_in = n;
}
ret = deflate(z, Z_NO_FLUSH);
} while (ret == Z_OK && z->avail_out > 0);
if (ret == Z_OK) {
zb->flags |= GOT_DEFLATE_F_HAVE_MORE;
} else {
if (ret != Z_STREAM_END)
return got_error(GOT_ERR_COMPRESSION);
zb->flags &= ~GOT_DEFLATE_F_HAVE_MORE;
}
*outlenp = z->total_out - last_total_out;
return NULL;
}
void
got_deflate_end(struct got_deflate_buf *zb)
{
free(zb->inbuf);
if (zb->flags & GOT_DEFLATE_F_OWN_OUTBUF)
free(zb->outbuf);
deflateEnd(&zb->z);
}
const struct got_error *
got_deflate_to_file(size_t *outlen, FILE *infile, FILE *outfile)
{
const struct got_error *err;
size_t avail;
struct got_deflate_buf zb;
err = got_deflate_init(&zb, NULL, GOT_DEFLATE_BUFSIZE);
if (err)
goto done;
*outlen = 0;
do {
err = got_deflate_read(&zb, infile, &avail);
if (err)
goto done;
if (avail > 0) {
size_t n;
n = fwrite(zb.outbuf, avail, 1, outfile);
if (n != 1) {
err = got_ferror(outfile, GOT_ERR_IO);
goto done;
}
*outlen += avail;
}
} while (zb.flags & GOT_DEFLATE_F_HAVE_MORE);
done:
if (err == NULL)
rewind(outfile);
got_deflate_end(&zb);
return err;
}
|
ThomasAdam/gameoftrees
|
libexec/got-read-tree/got-read-tree.c
|
<reponame>ThomasAdam/gameoftrees<filename>libexec/got-read-tree/got-read-tree.c
/*
* Copyright (c) 2018, 2019, 2020 <NAME> <<EMAIL>>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/time.h>
#include <stdint.h>
#include <limits.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sha1.h>
#include <unistd.h>
#include <zlib.h>
#include "got_compat.h"
#include "got_error.h"
#include "got_object.h"
#include "got_path.h"
#include "got_lib_delta.h"
#include "got_lib_inflate.h"
#include "got_lib_object.h"
#include "got_lib_object_parse.h"
#include "got_lib_privsep.h"
static volatile sig_atomic_t sigint_received;
static void
catch_sigint(int signo)
{
sigint_received = 1;
}
static const struct got_error *
read_tree_object(struct got_pathlist_head *entries, int *nentries,
uint8_t **p, FILE *f)
{
const struct got_error *err = NULL;
struct got_object *obj;
size_t len;
err = got_inflate_to_mem(p, &len, NULL, f);
if (err)
return err;
err = got_object_parse_header(&obj, *p, len);
if (err)
return err;
if (len < obj->hdrlen + obj->size) {
err = got_error(GOT_ERR_BAD_OBJ_DATA);
goto done;
}
/* Skip object header. */
len -= obj->hdrlen;
err = got_object_parse_tree(entries, nentries, *p + obj->hdrlen, len);
done:
got_object_close(obj);
return err;
}
int
main(int argc, char *argv[])
{
const struct got_error *err = NULL;
struct imsgbuf ibuf;
signal(SIGINT, catch_sigint);
imsg_init(&ibuf, GOT_IMSG_FD_CHILD);
#ifndef PROFILE
/* revoke access to most system calls */
if (pledge("stdio recvfd", NULL) == -1) {
err = got_error_from_errno("pledge");
got_privsep_send_error(&ibuf, err);
return 1;
}
#endif
for (;;) {
struct imsg imsg;
FILE *f = NULL;
struct got_pathlist_head entries;
int nentries = 0;
uint8_t *buf = NULL;
TAILQ_INIT(&entries);
if (sigint_received) {
err = got_error(GOT_ERR_CANCELLED);
break;
}
err = got_privsep_recv_imsg(&imsg, &ibuf, 0);
if (err) {
if (err->code == GOT_ERR_PRIVSEP_PIPE)
err = NULL;
break;
}
if (imsg.hdr.type == GOT_IMSG_STOP)
break;
if (imsg.hdr.type != GOT_IMSG_TREE_REQUEST) {
err = got_error(GOT_ERR_PRIVSEP_MSG);
goto done;
}
if (imsg.fd == -1) {
err = got_error(GOT_ERR_PRIVSEP_NO_FD);
goto done;
}
/* Always assume file offset zero. */
f = fdopen(imsg.fd, "rb");
if (f == NULL) {
err = got_error_from_errno("fdopen");
goto done;
}
err = read_tree_object(&entries, &nentries, &buf, f);
if (err)
goto done;
err = got_privsep_send_tree(&ibuf, &entries, nentries);
done:
got_object_parsed_tree_entries_free(&entries);
free(buf);
if (f) {
if (fclose(f) != 0 && err == NULL)
err = got_error_from_errno("fclose");
} else if (imsg.fd != -1) {
if (close(imsg.fd) != 0 && err == NULL)
err = got_error_from_errno("close");
}
imsg_free(&imsg);
if (err)
break;
}
imsg_clear(&ibuf);
if (err) {
if (!sigint_received && err->code != GOT_ERR_PRIVSEP_PIPE) {
fprintf(stderr, "%s: %s\n", getprogname(), err->msg);
got_privsep_send_error(&ibuf, err);
}
}
if (close(GOT_IMSG_FD_CHILD) != 0 && err == NULL)
err = got_error_from_errno("close");
return err ? 1 : 0;
}
|
ThomasAdam/gameoftrees
|
lib/got_lib_privsep.h
|
<filename>lib/got_lib_privsep.h<gh_stars>1-10
/*
* Copyright (c) 2018, 2019 <NAME> <<EMAIL>>
* Copyright (c) 2019, <NAME> <<EMAIL>>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* All code runs under the same UID but sensitive code paths are
* run in a separate process with tighter pledge(2) promises.
* Data is communicated between processes via imsg_flush(3) and imsg_read(3).
* This behaviour is transparent to users of the library.
*
* We generally transmit data in imsg buffers, split across several messages
* if necessary. File descriptors are used in cases where this is impractical,
* such as when accessing pack files or when transferring large blobs.
*
* We exec(2) after a fork(2). Parts of our library functionality are
* accessible via separate executables in a libexec directory.
*/
#define GOT_IMSG_FD_CHILD (STDERR_FILENO + 1)
#ifndef GOT_LIBEXECDIR
#define GOT_LIBEXECDIR /usr/local/bin
#endif
/* Names of helper programs in libexec directory */
#define GOT_PROG_READ_OBJECT got-read-object
#define GOT_PROG_READ_TREE got-read-tree
#define GOT_PROG_READ_COMMIT got-read-commit
#define GOT_PROG_READ_BLOB got-read-blob
#define GOT_PROG_READ_TAG got-read-tag
#define GOT_PROG_READ_PACK got-read-pack
#define GOT_PROG_READ_GITCONFIG got-read-gitconfig
#define GOT_PROG_READ_GOTCONFIG got-read-gotconfig
#define GOT_PROG_FETCH_PACK got-fetch-pack
#define GOT_PROG_INDEX_PACK got-index-pack
#define GOT_PROG_SEND_PACK got-send-pack
#define GOT_STRINGIFY(x) #x
#define GOT_STRINGVAL(x) GOT_STRINGIFY(x)
/* Paths to helper programs in libexec directory */
#define GOT_PATH_PROG_READ_OBJECT \
GOT_STRINGVAL(GOT_LIBEXECDIR) "/" GOT_STRINGVAL(GOT_PROG_READ_OBJECT)
#define GOT_PATH_PROG_READ_TREE \
GOT_STRINGVAL(GOT_LIBEXECDIR) "/" GOT_STRINGVAL(GOT_PROG_READ_TREE)
#define GOT_PATH_PROG_READ_COMMIT \
GOT_STRINGVAL(GOT_LIBEXECDIR) "/" GOT_STRINGVAL(GOT_PROG_READ_COMMIT)
#define GOT_PATH_PROG_READ_BLOB \
GOT_STRINGVAL(GOT_LIBEXECDIR) "/" GOT_STRINGVAL(GOT_PROG_READ_BLOB)
#define GOT_PATH_PROG_READ_TAG \
GOT_STRINGVAL(GOT_LIBEXECDIR) "/" GOT_STRINGVAL(GOT_PROG_READ_TAG)
#define GOT_PATH_PROG_READ_PACK \
GOT_STRINGVAL(GOT_LIBEXECDIR) "/" GOT_STRINGVAL(GOT_PROG_READ_PACK)
#define GOT_PATH_PROG_READ_GITCONFIG \
GOT_STRINGVAL(GOT_LIBEXECDIR) "/" GOT_STRINGVAL(GOT_PROG_READ_GITCONFIG)
#define GOT_PATH_PROG_READ_GOTCONFIG \
GOT_STRINGVAL(GOT_LIBEXECDIR) "/" GOT_STRINGVAL(GOT_PROG_READ_GOTCONFIG)
#define GOT_PATH_PROG_FETCH_PACK \
GOT_STRINGVAL(GOT_LIBEXECDIR) "/" GOT_STRINGVAL(GOT_PROG_FETCH_PACK)
#define GOT_PATH_PROG_SEND_PACK \
GOT_STRINGVAL(GOT_LIBEXECDIR) "/" GOT_STRINGVAL(GOT_PROG_SEND_PACK)
#define GOT_PATH_PROG_INDEX_PACK \
GOT_STRINGVAL(GOT_LIBEXECDIR) "/" GOT_STRINGVAL(GOT_PROG_INDEX_PACK)
struct got_privsep_child {
int imsg_fd;
pid_t pid;
struct imsgbuf *ibuf;
};
enum got_imsg_type {
/* An error occured while processing a request. */
GOT_IMSG_ERROR,
/* Stop the child process. */
GOT_IMSG_STOP,
/*
* Messages concerned with read access to objects in a repository.
* Object and pack files are opened by the main process, where
* data may be read as a byte string but without any interpretation.
* Decompression and parsing of object and pack files occurs in a
* separate process which runs under pledge("stdio recvfd").
* This sandboxes our own repository parsing code, as well as zlib.
*/
GOT_IMSG_OBJECT_REQUEST,
GOT_IMSG_OBJECT,
GOT_IMSG_COMMIT_REQUEST,
GOT_IMSG_COMMIT,
GOT_IMSG_COMMIT_LOGMSG,
GOT_IMSG_TREE_REQUEST,
GOT_IMSG_TREE,
GOT_IMSG_TREE_ENTRY,
GOT_IMSG_BLOB_REQUEST,
GOT_IMSG_BLOB_OUTFD,
GOT_IMSG_BLOB,
GOT_IMSG_TAG_REQUEST,
GOT_IMSG_TAG,
GOT_IMSG_TAG_TAGMSG,
/* Messages related to networking. */
GOT_IMSG_FETCH_REQUEST,
GOT_IMSG_FETCH_HAVE_REF,
GOT_IMSG_FETCH_WANTED_BRANCH,
GOT_IMSG_FETCH_WANTED_REF,
GOT_IMSG_FETCH_OUTFD,
GOT_IMSG_FETCH_SYMREFS,
GOT_IMSG_FETCH_REF,
GOT_IMSG_FETCH_SERVER_PROGRESS,
GOT_IMSG_FETCH_DOWNLOAD_PROGRESS,
GOT_IMSG_FETCH_DONE,
GOT_IMSG_IDXPACK_REQUEST,
GOT_IMSG_IDXPACK_OUTFD,
GOT_IMSG_IDXPACK_PROGRESS,
GOT_IMSG_IDXPACK_DONE,
/* Messages related to pack files. */
GOT_IMSG_PACKIDX,
GOT_IMSG_PACK,
GOT_IMSG_PACKED_OBJECT_REQUEST,
GOT_IMSG_COMMIT_TRAVERSAL_REQUEST,
GOT_IMSG_TRAVERSED_COMMITS,
GOT_IMSG_COMMIT_TRAVERSAL_DONE,
/* Message sending file descriptor to a temporary file. */
GOT_IMSG_TMPFD,
/* Messages related to gitconfig files. */
GOT_IMSG_GITCONFIG_PARSE_REQUEST,
GOT_IMSG_GITCONFIG_REPOSITORY_FORMAT_VERSION_REQUEST,
GOT_IMSG_GITCONFIG_REPOSITORY_EXTENSIONS_REQUEST,
GOT_IMSG_GITCONFIG_AUTHOR_NAME_REQUEST,
GOT_IMSG_GITCONFIG_AUTHOR_EMAIL_REQUEST,
GOT_IMSG_GITCONFIG_REMOTES_REQUEST,
GOT_IMSG_GITCONFIG_INT_VAL,
GOT_IMSG_GITCONFIG_STR_VAL,
GOT_IMSG_GITCONFIG_REMOTES,
GOT_IMSG_GITCONFIG_REMOTE,
GOT_IMSG_GITCONFIG_OWNER_REQUEST,
GOT_IMSG_GITCONFIG_OWNER,
/* Messages related to gotconfig files. */
GOT_IMSG_GOTCONFIG_PARSE_REQUEST,
GOT_IMSG_GOTCONFIG_AUTHOR_REQUEST,
GOT_IMSG_GOTCONFIG_REMOTES_REQUEST,
GOT_IMSG_GOTCONFIG_INT_VAL,
GOT_IMSG_GOTCONFIG_STR_VAL,
GOT_IMSG_GOTCONFIG_REMOTES,
GOT_IMSG_GOTCONFIG_REMOTE,
};
/* Structure for GOT_IMSG_ERROR. */
struct got_imsg_error {
int code; /* an error code from got_error.h */
int errno_code; /* in case code equals GOT_ERR_ERRNO */
} __attribute__((__packed__));
/*
* Structure for GOT_IMSG_TREE_REQUEST and GOT_IMSG_OBJECT data.
*/
struct got_imsg_object {
uint8_t id[SHA1_DIGEST_LENGTH];
/* These fields are the same as in struct got_object. */
int type;
int flags;
size_t hdrlen;
size_t size;
off_t pack_offset;
int pack_idx;
} __attribute__((__packed__));
/* Structure for GOT_IMSG_COMMIT data. */
struct got_imsg_commit_object {
uint8_t tree_id[SHA1_DIGEST_LENGTH];
size_t author_len;
time_t author_time;
time_t author_gmtoff;
size_t committer_len;
time_t committer_time;
time_t committer_gmtoff;
size_t logmsg_len;
int nparents;
/*
* Followed by author_len + committer_len data bytes
*/
/* Followed by 'nparents' SHA1_DIGEST_LENGTH length strings */
/*
* Followed by 'logmsg_len' bytes of commit log message data in
* one or more GOT_IMSG_COMMIT_LOGMSG messages.
*/
} __attribute__((__packed__));
/* Structure for GOT_IMSG_TREE_ENTRY. */
struct got_imsg_tree_entry {
char id[SHA1_DIGEST_LENGTH];
mode_t mode;
/* Followed by entry's name in remaining data of imsg buffer. */
} __attribute__((__packed__));
/* Structure for GOT_IMSG_TREE_OBJECT_REPLY data. */
struct got_imsg_tree_object {
int nentries; /* This many TREE_ENTRY messages follow. */
};
/* Structure for GOT_IMSG_BLOB. */
struct got_imsg_blob {
size_t size;
size_t hdrlen;
/*
* If size <= GOT_PRIVSEP_INLINE_BLOB_DATA_MAX, blob data follows
* in the imsg buffer. Otherwise, blob data has been written to a
* file descriptor passed via the GOT_IMSG_BLOB_OUTFD imsg.
*/
#define GOT_PRIVSEP_INLINE_BLOB_DATA_MAX \
(MAX_IMSGSIZE - IMSG_HEADER_SIZE - sizeof(struct got_imsg_blob))
};
/* Structure for GOT_IMSG_TAG data. */
struct got_imsg_tag_object {
uint8_t id[SHA1_DIGEST_LENGTH];
int obj_type;
size_t tag_len;
size_t tagger_len;
time_t tagger_time;
time_t tagger_gmtoff;
size_t tagmsg_len;
/*
* Followed by tag_len + tagger_len data bytes
*/
/*
* Followed by 'tagmsg_len' bytes of tag message data in
* one or more GOT_IMSG_TAG_TAGMSG messages.
*/
} __attribute__((__packed__));
/* Structure for GOT_IMSG_FETCH_HAVE_REF data. */
struct got_imsg_fetch_have_ref {
uint8_t id[SHA1_DIGEST_LENGTH];
size_t name_len;
/* Followed by name_len data bytes. */
} __attribute__((__packed__));
/* Structure for GOT_IMSG_FETCH_WANTED_BRANCH data. */
struct got_imsg_fetch_wanted_branch {
size_t name_len;
/* Followed by name_len data bytes. */
} __attribute__((__packed__));
/* Structure for GOT_IMSG_FETCH_WANTED_REF data. */
struct got_imsg_fetch_wanted_ref {
size_t name_len;
/* Followed by name_len data bytes. */
} __attribute__((__packed__));
/* Structure for GOT_IMSG_FETCH_REQUEST data. */
struct got_imsg_fetch_request {
int fetch_all_branches;
int list_refs_only;
int verbosity;
size_t n_have_refs;
size_t n_wanted_branches;
size_t n_wanted_refs;
/* Followed by n_have_refs GOT_IMSG_FETCH_HAVE_REF messages. */
/* Followed by n_wanted_branches times GOT_IMSG_FETCH_WANTED_BRANCH. */
/* Followed by n_wanted_refs times GOT_IMSG_FETCH_WANTED_REF. */
} __attribute__((__packed__));
/* Structures for GOT_IMSG_FETCH_SYMREFS data. */
struct got_imsg_fetch_symref {
size_t name_len;
size_t target_len;
/*
* Followed by name_len + target_len data bytes.
*/
} __attribute__((__packed__));
struct got_imsg_fetch_symrefs {
size_t nsymrefs;
/* Followed by nsymrefs times of got_imsg_fetch_symref data. */
} __attribute__((__packed__));
/* Structure for GOT_IMSG_FETCH_REF data. */
struct got_imsg_fetch_ref {
/* Describes a reference which will be fetched. */
uint8_t refid[SHA1_DIGEST_LENGTH];
/* Followed by reference name in remaining data of imsg buffer. */
};
/* Structure for GOT_IMSG_FETCH_DOWNLOAD_PROGRESS data. */
struct got_imsg_fetch_download_progress {
/* Number of packfile data bytes downloaded so far. */
off_t packfile_bytes;
};
/* Structure for GOT_IMSG_IDXPACK_REQUEST data. */
struct got_imsg_index_pack_request {
uint8_t pack_hash[SHA1_DIGEST_LENGTH];
} __attribute__((__packed__));
/* Structure for GOT_IMSG_IDXPACK_PROGRESS data. */
struct got_imsg_index_pack_progress {
/* Total number of objects in pack file. */
int nobj_total;
/* Number of objects indexed so far. */
int nobj_indexed;
/* Number of non-deltified objects in pack file. */
int nobj_loose;
/* Number of deltified objects resolved so far. */
int nobj_resolved;
};
/* Structure for GOT_IMSG_PACKIDX. */
struct got_imsg_packidx {
size_t len;
/* Additionally, a file desciptor is passed via imsg. */
};
/* Structure for GOT_IMSG_PACK. */
struct got_imsg_pack {
char path_packfile[PATH_MAX];
size_t filesize;
/* Additionally, a file desciptor is passed via imsg. */
} __attribute__((__packed__));
/*
* Structure for GOT_IMSG_PACKED_OBJECT_REQUEST data.
*/
struct got_imsg_packed_object {
uint8_t id[SHA1_DIGEST_LENGTH];
int idx;
} __attribute__((__packed__));
/* Structure for GOT_IMSG_COMMIT_TRAVERSAL_REQUEST */
struct got_imsg_commit_traversal_request {
uint8_t id[SHA1_DIGEST_LENGTH];
int idx;
size_t path_len;
/* Followed by path_len bytes of path data */
} __attribute__((__packed__));
/* Structure for GOT_IMSG_TRAVERSED_COMMITS */
struct got_imsg_traversed_commits {
size_t ncommits;
/* Followed by ncommit IDs of SHA1_DIGEST_LENGTH each */
} __attribute__((__packed__));
/*
* Structure for GOT_IMSG_GITCONFIG_REMOTE data.
*/
struct got_imsg_remote {
size_t name_len;
size_t url_len;
int mirror_references;
int fetch_all_branches;
int nbranches;
/* Followed by name_len + url_len data bytes. */
/* Followed by nbranches GOT_IMSG_GITCONFIG_STR_VAL messages. */
} __attribute__((__packed__));
/*
* Structure for GOT_IMSG_GITCONFIG_REMOTES data.
*/
struct got_imsg_remotes {
int nremotes; /* This many GOT_IMSG_GITCONFIG_REMOTE messages follow. */
};
struct got_remote_repo;
struct got_pack;
struct got_packidx;
struct got_pathlist_head;
const struct got_error *got_send_ack(pid_t);
const struct got_error *got_privsep_wait_for_child(pid_t);
const struct got_error *got_privsep_flush_imsg(struct imsgbuf *);
const struct got_error *got_privsep_send_stop(int);
const struct got_error *got_privsep_recv_imsg(struct imsg *, struct imsgbuf *,
size_t);
void got_privsep_send_error(struct imsgbuf *, const struct got_error *);
const struct got_error *got_privsep_send_ack(struct imsgbuf *);
const struct got_error *got_privsep_wait_ack(struct imsgbuf *);
const struct got_error *got_privsep_send_obj_req(struct imsgbuf *, int);
const struct got_error *got_privsep_send_commit_req(struct imsgbuf *, int,
struct got_object_id *, int);
const struct got_error *got_privsep_send_tree_req(struct imsgbuf *, int,
struct got_object_id *, int);
const struct got_error *got_privsep_send_tag_req(struct imsgbuf *, int,
struct got_object_id *, int);
const struct got_error *got_privsep_send_blob_req(struct imsgbuf *, int,
struct got_object_id *, int);
const struct got_error *got_privsep_send_blob_outfd(struct imsgbuf *, int);
const struct got_error *got_privsep_send_tmpfd(struct imsgbuf *, int);
const struct got_error *got_privsep_send_obj(struct imsgbuf *,
struct got_object *);
const struct got_error *got_privsep_send_index_pack_req(struct imsgbuf *,
uint8_t *, int);
const struct got_error *got_privsep_send_index_pack_outfd(struct imsgbuf *,
int);
const struct got_error *got_privsep_recv_index_progress(int *, int *, int *,
int *, int *, struct imsgbuf *ibuf);
const struct got_error *got_privsep_send_fetch_req(struct imsgbuf *, int,
struct got_pathlist_head *, int, struct got_pathlist_head *,
struct got_pathlist_head *, int, int);
const struct got_error *got_privsep_send_fetch_outfd(struct imsgbuf *, int);
const struct got_error *got_privsep_recv_fetch_progress(int *,
struct got_object_id **, char **, struct got_pathlist_head *, char **,
off_t *, uint8_t *, struct imsgbuf *);
const struct got_error *got_privsep_get_imsg_obj(struct got_object **,
struct imsg *, struct imsgbuf *);
const struct got_error *got_privsep_recv_obj(struct got_object **,
struct imsgbuf *);
const struct got_error *got_privsep_send_commit(struct imsgbuf *,
struct got_commit_object *);
const struct got_error *got_privsep_recv_commit(struct got_commit_object **,
struct imsgbuf *);
const struct got_error *got_privsep_recv_tree(struct got_tree_object **,
struct imsgbuf *);
const struct got_error *got_privsep_send_tree(struct imsgbuf *,
struct got_pathlist_head *, int);
const struct got_error *got_privsep_send_blob(struct imsgbuf *, size_t, size_t,
const uint8_t *);
const struct got_error *got_privsep_recv_blob(uint8_t **, size_t *, size_t *,
struct imsgbuf *);
const struct got_error *got_privsep_send_tag(struct imsgbuf *,
struct got_tag_object *);
const struct got_error *got_privsep_recv_tag(struct got_tag_object **,
struct imsgbuf *);
const struct got_error *got_privsep_init_pack_child(struct imsgbuf *,
struct got_pack *, struct got_packidx *);
const struct got_error *got_privsep_send_packed_obj_req(struct imsgbuf *, int,
struct got_object_id *);
const struct got_error *got_privsep_send_pack_child_ready(struct imsgbuf *);
const struct got_error *got_privsep_send_gitconfig_parse_req(struct imsgbuf *,
int);
const struct got_error *
got_privsep_send_gitconfig_repository_format_version_req(struct imsgbuf *);
const struct got_error *got_privsep_send_gitconfig_repository_extensions_req(
struct imsgbuf *);
const struct got_error *got_privsep_send_gitconfig_author_name_req(
struct imsgbuf *);
const struct got_error *got_privsep_send_gitconfig_author_email_req(
struct imsgbuf *);
const struct got_error *got_privsep_send_gitconfig_remotes_req(
struct imsgbuf *);
const struct got_error *got_privsep_send_gitconfig_owner_req(struct imsgbuf *);
const struct got_error *got_privsep_recv_gitconfig_str(char **,
struct imsgbuf *);
const struct got_error *got_privsep_recv_gitconfig_int(int *, struct imsgbuf *);
const struct got_error *got_privsep_recv_gitconfig_remotes(
struct got_remote_repo **, int *, struct imsgbuf *);
const struct got_error *got_privsep_send_gotconfig_parse_req(struct imsgbuf *,
int);
const struct got_error *got_privsep_send_gotconfig_author_req(struct imsgbuf *);
const struct got_error *got_privsep_send_gotconfig_remotes_req(
struct imsgbuf *);
const struct got_error *got_privsep_recv_gotconfig_str(char **,
struct imsgbuf *);
const struct got_error *got_privsep_recv_gotconfig_remotes(
struct got_remote_repo **, int *, struct imsgbuf *);
const struct got_error *got_privsep_send_commit_traversal_request(
struct imsgbuf *, struct got_object_id *, int, const char *);
const struct got_error *got_privsep_recv_traversed_commits(
struct got_commit_object **, struct got_object_id **,
struct got_object_id_queue *, struct imsgbuf *);
void got_privsep_exec_child(int[2], const char *, const char *);
|
ThomasAdam/gameoftrees
|
libexec/got-index-pack/got-index-pack.c
|
<reponame>ThomasAdam/gameoftrees
/*
* Copyright (c) 2019 <NAME> <<EMAIL>>
* Copyright (c) 2020 <NAME> <<EMAIL>>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/mman.h>
#include <stdint.h>
#include <errno.h>
#include <limits.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sha1.h>
#include <endian.h>
#include <fcntl.h>
#include <unistd.h>
#include <zlib.h>
#include <err.h>
#include <assert.h>
#include <dirent.h>
#include "got_error.h"
#include "got_object.h"
#include "got_compat.h"
#include "got_lib_sha1.h"
#include "got_lib_delta.h"
#include "got_lib_inflate.h"
#include "got_lib_object.h"
#include "got_lib_object_parse.h"
#include "got_lib_object_idset.h"
#include "got_lib_privsep.h"
#include "got_lib_pack.h"
#include "got_lib_delta_cache.h"
#ifndef nitems
#define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
#endif
struct got_indexed_object {
struct got_object_id id;
/*
* Has this object been fully resolved?
* If so, we know its ID, otherwise we don't and 'id' is invalid.
*/
int valid;
/* Offset of type+size field for this object in pack file. */
off_t off;
/* Type+size values parsed from pack file. */
uint8_t type;
uint64_t size;
/* Length of on-disk type+size data. */
size_t tslen;
/* Length of object data following type+size. */
size_t len;
uint32_t crc;
union {
struct {
/* For ref deltas. */
struct got_object_id ref_id;
} ref;
struct {
/* For offset deltas. */
off_t base_offset;
size_t base_offsetlen;
} ofs;
} delta;
};
static void
putbe32(char *b, uint32_t n)
{
b[0] = n >> 24;
b[1] = n >> 16;
b[2] = n >> 8;
b[3] = n >> 0;
}
static const struct got_error *
get_obj_type_label(const char **label, int obj_type)
{
const struct got_error *err = NULL;
switch (obj_type) {
case GOT_OBJ_TYPE_BLOB:
*label = GOT_OBJ_LABEL_BLOB;
break;
case GOT_OBJ_TYPE_TREE:
*label = GOT_OBJ_LABEL_TREE;
break;
case GOT_OBJ_TYPE_COMMIT:
*label = GOT_OBJ_LABEL_COMMIT;
break;
case GOT_OBJ_TYPE_TAG:
*label = GOT_OBJ_LABEL_TAG;
break;
default:
*label = NULL;
err = got_error(GOT_ERR_OBJ_TYPE);
break;
}
return err;
}
static const struct got_error *
read_checksum(uint32_t *crc, SHA1_CTX *sha1_ctx, int fd, size_t len)
{
uint8_t buf[8192];
size_t n;
ssize_t r;
for (n = len; n > 0; n -= r){
r = read(fd, buf, n > sizeof(buf) ? sizeof(buf) : n);
if (r == -1)
return got_error_from_errno("read");
if (r == 0)
break;
if (crc)
*crc = crc32(*crc, buf, r);
if (sha1_ctx)
SHA1Update(sha1_ctx, buf, r);
}
return NULL;
}
static const struct got_error *
read_file_sha1(SHA1_CTX *ctx, FILE *f, size_t len)
{
uint8_t buf[8192];
size_t n, r;
for (n = len; n > 0; n -= r) {
r = fread(buf, 1, n > sizeof(buf) ? sizeof(buf) : n, f);
if (r == 0) {
if (feof(f))
return NULL;
return got_ferror(f, GOT_ERR_IO);
}
SHA1Update(ctx, buf, r);
}
return NULL;
}
static const struct got_error *
read_packed_object(struct got_pack *pack, struct got_indexed_object *obj,
FILE *tmpfile, SHA1_CTX *pack_sha1_ctx)
{
const struct got_error *err = NULL;
SHA1_CTX ctx;
uint8_t *data = NULL;
size_t datalen = 0;
ssize_t n;
char *header;
size_t headerlen;
const char *obj_label;
size_t mapoff = obj->off;
struct got_inflate_checksum csum;
csum.input_sha1 = pack_sha1_ctx;
csum.input_crc = &obj->crc;
err = got_pack_parse_object_type_and_size(&obj->type, &obj->size,
&obj->tslen, pack, obj->off);
if (err)
return err;
if (pack->map) {
obj->crc = crc32(obj->crc, pack->map + mapoff, obj->tslen);
SHA1Update(pack_sha1_ctx, pack->map + mapoff, obj->tslen);
mapoff += obj->tslen;
} else {
/* XXX Seek back and get the CRC of on-disk type+size bytes. */
if (lseek(pack->fd, obj->off, SEEK_SET) == -1)
return got_error_from_errno("lseek");
err = read_checksum(&obj->crc, pack_sha1_ctx,
pack->fd, obj->tslen);
if (err)
return err;
}
switch (obj->type) {
case GOT_OBJ_TYPE_BLOB:
case GOT_OBJ_TYPE_COMMIT:
case GOT_OBJ_TYPE_TREE:
case GOT_OBJ_TYPE_TAG:
if (obj->size > GOT_DELTA_RESULT_SIZE_CACHED_MAX) {
if (fseek(tmpfile, 0L, SEEK_SET) == -1) {
err = got_error_from_errno("fseek");
break;
}
if (pack->map) {
err = got_inflate_to_file_mmap(&datalen,
&obj->len, &csum, pack->map, mapoff,
pack->filesize - mapoff, tmpfile);
} else {
err = got_inflate_to_file_fd(&datalen,
&obj->len, &csum, pack->fd, tmpfile);
}
} else {
if (pack->map) {
err = got_inflate_to_mem_mmap(&data, &datalen,
&obj->len, &csum, pack->map, mapoff,
pack->filesize - mapoff);
} else {
err = got_inflate_to_mem_fd(&data, &datalen,
&obj->len, &csum, obj->size, pack->fd);
}
}
if (err)
break;
SHA1Init(&ctx);
err = get_obj_type_label(&obj_label, obj->type);
if (err) {
free(data);
break;
}
if (asprintf(&header, "%s %lld", obj_label,
(long long)obj->size) == -1) {
err = got_error_from_errno("asprintf");
free(data);
break;
}
headerlen = strlen(header) + 1;
SHA1Update(&ctx, header, headerlen);
if (obj->size > GOT_DELTA_RESULT_SIZE_CACHED_MAX) {
err = read_file_sha1(&ctx, tmpfile, datalen);
if (err)
break;
} else
SHA1Update(&ctx, data, datalen);
SHA1Final(obj->id.sha1, &ctx);
free(header);
free(data);
break;
case GOT_OBJ_TYPE_REF_DELTA:
memset(obj->id.sha1, 0xff, SHA1_DIGEST_LENGTH);
if (pack->map) {
if (mapoff + SHA1_DIGEST_LENGTH >= pack->filesize) {
err = got_error(GOT_ERR_BAD_PACKFILE);
break;
}
memcpy(obj->delta.ref.ref_id.sha1, pack->map + mapoff,
SHA1_DIGEST_LENGTH);
obj->crc = crc32(obj->crc, pack->map + mapoff,
SHA1_DIGEST_LENGTH);
SHA1Update(pack_sha1_ctx, pack->map + mapoff,
SHA1_DIGEST_LENGTH);
mapoff += SHA1_DIGEST_LENGTH;
err = got_inflate_to_mem_mmap(NULL, &datalen,
&obj->len, &csum, pack->map, mapoff,
pack->filesize - mapoff);
if (err)
break;
} else {
n = read(pack->fd, obj->delta.ref.ref_id.sha1,
SHA1_DIGEST_LENGTH);
if (n == -1) {
err = got_error_from_errno("read");
break;
}
if (n < sizeof(obj->id)) {
err = got_error(GOT_ERR_BAD_PACKFILE);
break;
}
obj->crc = crc32(obj->crc, obj->delta.ref.ref_id.sha1,
SHA1_DIGEST_LENGTH);
SHA1Update(pack_sha1_ctx, obj->delta.ref.ref_id.sha1,
SHA1_DIGEST_LENGTH);
err = got_inflate_to_mem_fd(NULL, &datalen, &obj->len,
&csum, obj->size, pack->fd);
if (err)
break;
}
obj->len += SHA1_DIGEST_LENGTH;
break;
case GOT_OBJ_TYPE_OFFSET_DELTA:
memset(obj->id.sha1, 0xff, SHA1_DIGEST_LENGTH);
err = got_pack_parse_offset_delta(&obj->delta.ofs.base_offset,
&obj->delta.ofs.base_offsetlen, pack, obj->off,
obj->tslen);
if (err)
break;
if (pack->map) {
obj->crc = crc32(obj->crc, pack->map + mapoff,
obj->delta.ofs.base_offsetlen);
SHA1Update(pack_sha1_ctx, pack->map + mapoff,
obj->delta.ofs.base_offsetlen);
mapoff += obj->delta.ofs.base_offsetlen;
err = got_inflate_to_mem_mmap(NULL, &datalen,
&obj->len, &csum, pack->map, mapoff,
pack->filesize - mapoff);
if (err)
break;
} else {
/*
* XXX Seek back and get CRC and SHA1 of on-disk
* offset bytes.
*/
if (lseek(pack->fd, obj->off + obj->tslen, SEEK_SET)
== -1) {
err = got_error_from_errno("lseek");
break;
}
err = read_checksum(&obj->crc, pack_sha1_ctx,
pack->fd, obj->delta.ofs.base_offsetlen);
if (err)
break;
err = got_inflate_to_mem_fd(NULL, &datalen, &obj->len,
&csum, obj->size, pack->fd);
if (err)
break;
}
obj->len += obj->delta.ofs.base_offsetlen;
break;
default:
err = got_error(GOT_ERR_OBJ_TYPE);
break;
}
return err;
}
static const struct got_error *
hwrite(int fd, void *buf, int len, SHA1_CTX *ctx)
{
ssize_t w;
SHA1Update(ctx, buf, len);
w = write(fd, buf, len);
if (w == -1)
return got_error_from_errno("write");
if (w != len)
return got_error(GOT_ERR_IO);
return NULL;
}
static const struct got_error *
resolve_deltified_object(struct got_pack *pack, struct got_packidx *packidx,
struct got_indexed_object *obj, FILE *tmpfile, FILE *delta_base_file,
FILE *delta_accum_file)
{
const struct got_error *err = NULL;
struct got_delta_chain deltas;
struct got_delta *delta;
uint8_t *buf = NULL;
size_t len = 0;
SHA1_CTX ctx;
char *header = NULL;
size_t headerlen;
uint64_t max_size;
int base_obj_type;
const char *obj_label;
deltas.nentries = 0;
SIMPLEQ_INIT(&deltas.entries);
err = got_pack_resolve_delta_chain(&deltas, packidx, pack,
obj->off, obj->tslen, obj->type, obj->size,
GOT_DELTA_CHAIN_RECURSION_MAX);
if (err)
goto done;
err = got_pack_get_delta_chain_max_size(&max_size, &deltas, pack);
if (err)
goto done;
if (max_size > GOT_DELTA_RESULT_SIZE_CACHED_MAX) {
rewind(tmpfile);
rewind(delta_base_file);
rewind(delta_accum_file);
err = got_pack_dump_delta_chain_to_file(&len, &deltas,
pack, tmpfile, delta_base_file, delta_accum_file);
if (err)
goto done;
} else {
err = got_pack_dump_delta_chain_to_mem(&buf, &len,
&deltas, pack);
}
if (err)
goto done;
err = got_delta_chain_get_base_type(&base_obj_type, &deltas);
if (err)
goto done;
err = get_obj_type_label(&obj_label, base_obj_type);
if (err)
goto done;
if (asprintf(&header, "%s %zd", obj_label, len) == -1) {
err = got_error_from_errno("asprintf");
goto done;
}
headerlen = strlen(header) + 1;
SHA1Init(&ctx);
SHA1Update(&ctx, header, headerlen);
if (max_size > GOT_DELTA_RESULT_SIZE_CACHED_MAX) {
err = read_file_sha1(&ctx, tmpfile, len);
if (err)
goto done;
} else
SHA1Update(&ctx, buf, len);
SHA1Final(obj->id.sha1, &ctx);
done:
free(buf);
free(header);
while (!SIMPLEQ_EMPTY(&deltas.entries)) {
delta = SIMPLEQ_FIRST(&deltas.entries);
SIMPLEQ_REMOVE_HEAD(&deltas.entries, entry);
free(delta);
}
return err;
}
/* Determine the slot in the pack index a given object ID should use. */
static int
find_object_idx(struct got_packidx *packidx, uint8_t *sha1)
{
u_int8_t id0 = sha1[0];
uint32_t nindexed = be32toh(packidx->hdr.fanout_table[0xff]);
int left = 0, right = nindexed - 1;
int cmp = 0, i = 0;
if (id0 > 0)
left = be32toh(packidx->hdr.fanout_table[id0 - 1]);
while (left <= right) {
struct got_packidx_object_id *oid;
i = ((left + right) / 2);
oid = &packidx->hdr.sorted_ids[i];
cmp = memcmp(sha1, oid->sha1, SHA1_DIGEST_LENGTH);
if (cmp == 0)
return -1; /* object already indexed */
else if (cmp > 0)
left = i + 1;
else if (cmp < 0)
right = i - 1;
}
return left;
}
#if 0
static void
print_packidx(struct got_packidx *packidx)
{
uint32_t nindexed = be32toh(packidx->hdr.fanout_table[0xff]);
int i;
fprintf(stderr, "object IDs:\n");
for (i = 0; i < nindexed; i++) {
char hex[SHA1_DIGEST_STRING_LENGTH];
got_sha1_digest_to_str(packidx->hdr.sorted_ids[i].sha1,
hex, sizeof(hex));
fprintf(stderr, "%s\n", hex);
}
fprintf(stderr, "\n");
fprintf(stderr, "object offsets:\n");
for (i = 0; i < nindexed; i++) {
uint32_t offset = be32toh(packidx->hdr.offsets[i]);
if (offset & GOT_PACKIDX_OFFSET_VAL_IS_LARGE_IDX) {
int j = offset & GOT_PACKIDX_OFFSET_VAL_MASK;
fprintf(stderr, "%u -> %llu\n", offset,
be64toh(packidx->hdr.large_offsets[j]));
} else
fprintf(stderr, "%u\n", offset);
}
fprintf(stderr, "\n");
fprintf(stderr, "fanout table:");
for (i = 0; i <= 0xff; i++)
fprintf(stderr, " %u", be32toh(packidx->hdr.fanout_table[i]));
fprintf(stderr, "\n");
}
#endif
static void
add_indexed_object(struct got_packidx *packidx, uint32_t idx,
struct got_indexed_object *obj)
{
int i;
memcpy(packidx->hdr.sorted_ids[idx].sha1, obj->id.sha1,
SHA1_DIGEST_LENGTH);
packidx->hdr.crc32[idx] = htobe32(obj->crc);
if (obj->off < GOT_PACKIDX_OFFSET_VAL_IS_LARGE_IDX)
packidx->hdr.offsets[idx] = htobe32(obj->off);
else {
packidx->hdr.offsets[idx] = htobe32(packidx->nlargeobj |
GOT_PACKIDX_OFFSET_VAL_IS_LARGE_IDX);
packidx->hdr.large_offsets[packidx->nlargeobj] =
htobe64(obj->off);
packidx->nlargeobj++;
}
for (i = obj->id.sha1[0]; i <= 0xff; i++) {
uint32_t n = be32toh(packidx->hdr.fanout_table[i]);
packidx->hdr.fanout_table[i] = htobe32(n + 1);
}
}
static int
indexed_obj_cmp(const void *pa, const void *pb)
{
struct got_indexed_object *a, *b;
a = (struct got_indexed_object *)pa;
b = (struct got_indexed_object *)pb;
return got_object_id_cmp(&a->id, &b->id);
}
static void
make_packidx(struct got_packidx *packidx, int nobj,
struct got_indexed_object *objects)
{
struct got_indexed_object *obj;
int i;
uint32_t idx = 0;
qsort(objects, nobj, sizeof(struct got_indexed_object),
indexed_obj_cmp);
memset(packidx->hdr.fanout_table, 0,
GOT_PACKIDX_V2_FANOUT_TABLE_ITEMS * sizeof(uint32_t));
packidx->nlargeobj = 0;
for (i = 0; i < nobj; i++) {
obj = &objects[i];
if (obj->valid)
add_indexed_object(packidx, idx++, obj);
}
}
static void
update_packidx(struct got_packidx *packidx, int nobj,
struct got_indexed_object *obj)
{
int idx;
uint32_t nindexed = be32toh(packidx->hdr.fanout_table[0xff]);
idx = find_object_idx(packidx, obj->id.sha1);
if (idx == -1) {
char hex[SHA1_DIGEST_STRING_LENGTH];
got_sha1_digest_to_str(obj->id.sha1, hex, sizeof(hex));
return; /* object already indexed */
}
memmove(&packidx->hdr.sorted_ids[idx + 1],
&packidx->hdr.sorted_ids[idx],
sizeof(struct got_packidx_object_id) * (nindexed - idx));
memmove(&packidx->hdr.offsets[idx + 1], &packidx->hdr.offsets[idx],
sizeof(uint32_t) * (nindexed - idx));
add_indexed_object(packidx, idx, obj);
}
static const struct got_error *
send_index_pack_progress(struct imsgbuf *ibuf, int nobj_total,
int nobj_indexed, int nobj_loose, int nobj_resolved)
{
struct got_imsg_index_pack_progress iprogress;
iprogress.nobj_total = nobj_total;
iprogress.nobj_indexed = nobj_indexed;
iprogress.nobj_loose = nobj_loose;
iprogress.nobj_resolved = nobj_resolved;
if (imsg_compose(ibuf, GOT_IMSG_IDXPACK_PROGRESS, 0, 0, -1,
&iprogress, sizeof(iprogress)) == -1)
return got_error_from_errno("imsg_compose IDXPACK_PROGRESS");
return got_privsep_flush_imsg(ibuf);
}
static const struct got_error *
send_index_pack_done(struct imsgbuf *ibuf)
{
if (imsg_compose(ibuf, GOT_IMSG_IDXPACK_DONE, 0, 0, -1, NULL, 0) == -1)
return got_error_from_errno("imsg_compose FETCH");
return got_privsep_flush_imsg(ibuf);
}
static const struct got_error *
index_pack(struct got_pack *pack, int idxfd, FILE *tmpfile,
FILE *delta_base_file, FILE *delta_accum_file, uint8_t *pack_sha1_expected,
struct imsgbuf *ibuf)
{
const struct got_error *err;
struct got_packfile_hdr hdr;
struct got_packidx packidx;
char buf[8];
char pack_sha1[SHA1_DIGEST_LENGTH];
int nobj, nvalid, nloose, nresolved = 0, i;
struct got_indexed_object *objects = NULL, *obj;
SHA1_CTX ctx;
uint8_t packidx_hash[SHA1_DIGEST_LENGTH];
ssize_t r, w;
int pass, have_ref_deltas = 0, first_delta_idx = -1;
size_t mapoff = 0;
int p_indexed = 0, last_p_indexed = -1;
int p_resolved = 0, last_p_resolved = -1;
/* Require that pack file header and SHA1 trailer are present. */
if (pack->filesize < sizeof(hdr) + SHA1_DIGEST_LENGTH)
return got_error_msg(GOT_ERR_BAD_PACKFILE,
"short pack file");
if (pack->map) {
memcpy(&hdr, pack->map, sizeof(hdr));
mapoff += sizeof(hdr);
} else {
r = read(pack->fd, &hdr, sizeof(hdr));
if (r == -1)
return got_error_from_errno("read");
if (r < sizeof(hdr))
return got_error_msg(GOT_ERR_BAD_PACKFILE,
"short pack file");
}
if (hdr.signature != htobe32(GOT_PACKFILE_SIGNATURE))
return got_error_msg(GOT_ERR_BAD_PACKFILE,
"bad packfile signature");
if (hdr.version != htobe32(GOT_PACKFILE_VERSION))
return got_error_msg(GOT_ERR_BAD_PACKFILE,
"bad packfile version");
nobj = be32toh(hdr.nobjects);
if (nobj == 0)
return got_error_msg(GOT_ERR_BAD_PACKFILE,
"bad packfile with zero objects");
/* We compute the SHA1 of pack file contents and verify later on. */
SHA1Init(&ctx);
SHA1Update(&ctx, (void *)&hdr, sizeof(hdr));
/*
* Create an in-memory pack index which will grow as objects
* IDs in the pack file are discovered. Only fields used to
* read deltified objects will be needed by the pack.c library
* code, so setting up just a pack index header is sufficient.
*/
memset(&packidx, 0, sizeof(packidx));
packidx.hdr.magic = malloc(sizeof(uint32_t));
if (packidx.hdr.magic == NULL)
return got_error_from_errno("calloc");
*packidx.hdr.magic = htobe32(GOT_PACKIDX_V2_MAGIC);
packidx.hdr.version = malloc(sizeof(uint32_t));
if (packidx.hdr.version == NULL) {
err = got_error_from_errno("malloc");
goto done;
}
*packidx.hdr.version = htobe32(GOT_PACKIDX_VERSION);
packidx.hdr.fanout_table = calloc(GOT_PACKIDX_V2_FANOUT_TABLE_ITEMS,
sizeof(uint32_t));
if (packidx.hdr.fanout_table == NULL) {
err = got_error_from_errno("calloc");
goto done;
}
packidx.hdr.sorted_ids = calloc(nobj,
sizeof(struct got_packidx_object_id));
if (packidx.hdr.sorted_ids == NULL) {
err = got_error_from_errno("calloc");
goto done;
}
packidx.hdr.crc32 = calloc(nobj, sizeof(uint32_t));
if (packidx.hdr.crc32 == NULL) {
err = got_error_from_errno("calloc");
goto done;
}
packidx.hdr.offsets = calloc(nobj, sizeof(uint32_t));
if (packidx.hdr.offsets == NULL) {
err = got_error_from_errno("calloc");
goto done;
}
/* Large offsets table is empty for pack files < 2 GB. */
if (pack->filesize >= GOT_PACKIDX_OFFSET_VAL_IS_LARGE_IDX) {
packidx.hdr.large_offsets = calloc(nobj, sizeof(uint64_t));
if (packidx.hdr.large_offsets == NULL) {
err = got_error_from_errno("calloc");
goto done;
}
}
nvalid = 0;
nloose = 0;
objects = calloc(nobj, sizeof(struct got_indexed_object));
if (objects == NULL)
return got_error_from_errno("calloc");
/*
* First pass: locate all objects and identify un-deltified objects.
*
* When this pass has completed we will know offset, type, size, and
* CRC information for all objects in this pack file. We won't know
* any of the actual object IDs of deltified objects yet since we
* will not yet attempt to combine deltas.
*/
pass = 1;
for (i = 0; i < nobj; i++) {
/* Don't send too many progress privsep messages. */
p_indexed = ((i + 1) * 100) / nobj;
if (p_indexed != last_p_indexed) {
err = send_index_pack_progress(ibuf, nobj, i + 1,
nloose, 0);
if (err)
goto done;
last_p_indexed = p_indexed;
}
obj = &objects[i];
obj->crc = crc32(0L, NULL, 0);
/* Store offset to type+size information for this object. */
if (pack->map) {
obj->off = mapoff;
} else {
obj->off = lseek(pack->fd, 0, SEEK_CUR);
if (obj->off == -1) {
err = got_error_from_errno("lseek");
goto done;
}
}
err = read_packed_object(pack, obj, tmpfile, &ctx);
if (err)
goto done;
if (pack->map) {
mapoff += obj->tslen + obj->len;
} else {
if (lseek(pack->fd, obj->off + obj->tslen + obj->len,
SEEK_SET) == -1) {
err = got_error_from_errno("lseek");
goto done;
}
}
if (obj->type == GOT_OBJ_TYPE_BLOB ||
obj->type == GOT_OBJ_TYPE_TREE ||
obj->type == GOT_OBJ_TYPE_COMMIT ||
obj->type == GOT_OBJ_TYPE_TAG) {
obj->valid = 1;
nloose++;
} else {
if (first_delta_idx == -1)
first_delta_idx = i;
if (obj->type == GOT_OBJ_TYPE_REF_DELTA)
have_ref_deltas = 1;
}
}
nvalid = nloose;
/*
* Having done a full pass over the pack file and can now
* verify its checksum.
*/
SHA1Final(pack_sha1, &ctx);
if (memcmp(pack_sha1_expected, pack_sha1, SHA1_DIGEST_LENGTH) != 0) {
err = got_error_msg(GOT_ERR_BAD_PACKFILE,
"pack file checksum mismatch");
goto done;
}
/* Verify the SHA1 checksum stored at the end of the pack file. */
if (pack->map) {
memcpy(pack_sha1_expected, pack->map +
pack->filesize - SHA1_DIGEST_LENGTH,
SHA1_DIGEST_LENGTH);
} else {
ssize_t n;
if (lseek(pack->fd, -SHA1_DIGEST_LENGTH, SEEK_END) == -1) {
err = got_error_from_errno("lseek");
goto done;
}
n = read(pack->fd, pack_sha1_expected, SHA1_DIGEST_LENGTH);
if (n == -1) {
err = got_error_from_errno("read");
goto done;
}
if (n != SHA1_DIGEST_LENGTH) {
err = got_error(GOT_ERR_IO);
goto done;
}
}
if (memcmp(pack_sha1, pack_sha1_expected, SHA1_DIGEST_LENGTH) != 0) {
err = got_error_msg(GOT_ERR_BAD_PACKFILE,
"bad checksum in pack file trailer");
goto done;
}
if (first_delta_idx == -1)
first_delta_idx = 0;
/* In order to resolve ref deltas we need an in-progress pack index. */
if (have_ref_deltas)
make_packidx(&packidx, nobj, objects);
/*
* Second pass: We can now resolve deltas to compute the IDs of
* objects which appear in deltified form. Because deltas can be
* chained this pass may require a couple of iterations until all
* IDs of deltified objects have been discovered.
*/
pass++;
while (nvalid != nobj) {
int n = 0;
/*
* This loop will only run once unless the pack file
* contains ref deltas which refer to objects located
* later in the pack file, which is unusual.
* Offset deltas can always be resolved in one pass
* unless the packfile is corrupt.
*/
for (i = first_delta_idx; i < nobj; i++) {
obj = &objects[i];
if (obj->type != GOT_OBJ_TYPE_REF_DELTA &&
obj->type != GOT_OBJ_TYPE_OFFSET_DELTA)
continue;
if (obj->valid)
continue;
if (pack->map == NULL && lseek(pack->fd,
obj->off + obj->tslen, SEEK_SET) == -1) {
err = got_error_from_errno("lseek");
goto done;
}
err = resolve_deltified_object(pack, &packidx, obj,
tmpfile, delta_base_file, delta_accum_file);
if (err) {
if (err->code != GOT_ERR_NO_OBJ)
goto done;
/*
* We cannot resolve this object yet because
* a delta base is unknown. Try again later.
*/
continue;
}
obj->valid = 1;
n++;
if (have_ref_deltas)
update_packidx(&packidx, nobj, obj);
/* Don't send too many progress privsep messages. */
p_resolved = ((nresolved + n) * 100) / nobj;
if (p_resolved != last_p_resolved) {
err = send_index_pack_progress(ibuf, nobj,
nobj, nloose, nresolved + n);
if (err)
goto done;
last_p_resolved = p_resolved;
}
}
if (pass++ > 3 && n == 0) {
static char msg[64];
snprintf(msg, sizeof(msg), "could not resolve "
"any of deltas; packfile could be corrupt");
err = got_error_msg(GOT_ERR_BAD_PACKFILE, msg);
goto done;
}
nresolved += n;
nvalid += nresolved;
}
if (nloose + nresolved != nobj) {
static char msg[64];
snprintf(msg, sizeof(msg), "discovered only %d of %d objects",
nloose + nresolved, nobj);
err = got_error_msg(GOT_ERR_BAD_PACKFILE, msg);
goto done;
}
err = send_index_pack_progress(ibuf, nobj, nobj, nloose, nresolved);
if (err)
goto done;
make_packidx(&packidx, nobj, objects);
free(objects);
objects = NULL;
SHA1Init(&ctx);
putbe32(buf, GOT_PACKIDX_V2_MAGIC);
putbe32(buf + 4, GOT_PACKIDX_VERSION);
err = hwrite(idxfd, buf, 8, &ctx);
if (err)
goto done;
err = hwrite(idxfd, packidx.hdr.fanout_table,
GOT_PACKIDX_V2_FANOUT_TABLE_ITEMS * sizeof(uint32_t), &ctx);
if (err)
goto done;
err = hwrite(idxfd, packidx.hdr.sorted_ids,
nobj * SHA1_DIGEST_LENGTH, &ctx);
if (err)
goto done;
err = hwrite(idxfd, packidx.hdr.crc32, nobj * sizeof(uint32_t), &ctx);
if (err)
goto done;
err = hwrite(idxfd, packidx.hdr.offsets, nobj * sizeof(uint32_t),
&ctx);
if (err)
goto done;
if (packidx.nlargeobj > 0) {
err = hwrite(idxfd, packidx.hdr.large_offsets,
packidx.nlargeobj * sizeof(uint64_t), &ctx);
if (err)
goto done;
}
err = hwrite(idxfd, pack_sha1, SHA1_DIGEST_LENGTH, &ctx);
if (err)
goto done;
SHA1Final(packidx_hash, &ctx);
w = write(idxfd, packidx_hash, sizeof(packidx_hash));
if (w == -1) {
err = got_error_from_errno("write");
goto done;
}
if (w != sizeof(packidx_hash)) {
err = got_error(GOT_ERR_IO);
goto done;
}
done:
free(objects);
free(packidx.hdr.magic);
free(packidx.hdr.version);
free(packidx.hdr.fanout_table);
free(packidx.hdr.sorted_ids);
free(packidx.hdr.offsets);
free(packidx.hdr.large_offsets);
return err;
}
int
main(int argc, char **argv)
{
const struct got_error *err = NULL, *close_err;
struct imsgbuf ibuf;
struct imsg imsg;
size_t i;
int idxfd = -1, tmpfd = -1;
FILE *tmpfiles[3];
struct got_pack pack;
uint8_t pack_hash[SHA1_DIGEST_LENGTH];
off_t packfile_size;
#if 0
static int attached;
while (!attached)
sleep(1);
#endif
for (i = 0; i < nitems(tmpfiles); i++)
tmpfiles[i] = NULL;
memset(&pack, 0, sizeof(pack));
pack.fd = -1;
pack.delta_cache = got_delta_cache_alloc(500,
GOT_DELTA_RESULT_SIZE_CACHED_MAX);
if (pack.delta_cache == NULL) {
err = got_error_from_errno("got_delta_cache_alloc");
goto done;
}
imsg_init(&ibuf, GOT_IMSG_FD_CHILD);
#ifndef PROFILE
/* revoke access to most system calls */
if (pledge("stdio recvfd", NULL) == -1) {
err = got_error_from_errno("pledge");
got_privsep_send_error(&ibuf, err);
return 1;
}
#endif
err = got_privsep_recv_imsg(&imsg, &ibuf, 0);
if (err)
goto done;
if (imsg.hdr.type == GOT_IMSG_STOP)
goto done;
if (imsg.hdr.type != GOT_IMSG_IDXPACK_REQUEST) {
err = got_error(GOT_ERR_PRIVSEP_MSG);
goto done;
}
if (imsg.hdr.len - IMSG_HEADER_SIZE != sizeof(pack_hash)) {
err = got_error(GOT_ERR_PRIVSEP_LEN);
goto done;
}
memcpy(pack_hash, imsg.data, sizeof(pack_hash));
pack.fd = imsg.fd;
err = got_privsep_recv_imsg(&imsg, &ibuf, 0);
if (err)
goto done;
if (imsg.hdr.type == GOT_IMSG_STOP)
goto done;
if (imsg.hdr.type != GOT_IMSG_IDXPACK_OUTFD) {
err = got_error(GOT_ERR_PRIVSEP_MSG);
goto done;
}
if (imsg.hdr.len - IMSG_HEADER_SIZE != 0) {
err = got_error(GOT_ERR_PRIVSEP_LEN);
goto done;
}
idxfd = imsg.fd;
for (i = 0; i < nitems(tmpfiles); i++) {
err = got_privsep_recv_imsg(&imsg, &ibuf, 0);
if (err)
goto done;
if (imsg.hdr.type == GOT_IMSG_STOP)
goto done;
if (imsg.hdr.type != GOT_IMSG_TMPFD) {
err = got_error(GOT_ERR_PRIVSEP_MSG);
goto done;
}
if (imsg.hdr.len - IMSG_HEADER_SIZE != 0) {
err = got_error(GOT_ERR_PRIVSEP_LEN);
goto done;
}
tmpfd = imsg.fd;
tmpfiles[i] = fdopen(tmpfd, "w+");
if (tmpfiles[i] == NULL) {
err = got_error_from_errno("fdopen");
goto done;
}
tmpfd = -1;
}
if (lseek(pack.fd, 0, SEEK_END) == -1) {
err = got_error_from_errno("lseek");
goto done;
}
packfile_size = lseek(pack.fd, 0, SEEK_CUR);
if (packfile_size == -1) {
err = got_error_from_errno("lseek");
goto done;
}
pack.filesize = packfile_size; /* XXX off_t vs size_t */
if (lseek(pack.fd, 0, SEEK_SET) == -1) {
err = got_error_from_errno("lseek");
goto done;
}
#ifndef GOT_PACK_NO_MMAP
pack.map = mmap(NULL, pack.filesize, PROT_READ, MAP_PRIVATE,
pack.fd, 0);
if (pack.map == MAP_FAILED)
pack.map = NULL; /* fall back to read(2) */
#endif
err = index_pack(&pack, idxfd, tmpfiles[0], tmpfiles[1], tmpfiles[2],
pack_hash, &ibuf);
done:
close_err = got_pack_close(&pack);
if (close_err && err == NULL)
err = close_err;
if (idxfd != -1 && close(idxfd) == -1 && err == NULL)
err = got_error_from_errno("close");
if (tmpfd != -1 && close(tmpfd) == -1 && err == NULL)
err = got_error_from_errno("close");
for (i = 0; i < nitems(tmpfiles); i++) {
if (tmpfiles[i] != NULL && fclose(tmpfiles[i]) == EOF &&
err == NULL)
err = got_error_from_errno("close");
}
if (err == NULL)
err = send_index_pack_done(&ibuf);
if (err) {
got_privsep_send_error(&ibuf, err);
fprintf(stderr, "%s: %s\n", getprogname(), err->msg);
got_privsep_send_error(&ibuf, err);
exit(1);
}
exit(0);
}
|
ThomasAdam/gameoftrees
|
lib/diff_output_unidiff.c
|
/* Produce a unidiff output from a diff_result. */
/*
* Copyright (c) 2020 <NAME> <<EMAIL>>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <errno.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <arraylist.h>
#include <diff_main.h>
#include <diff_output.h>
#include "diff_internal.h"
#include "diff_debug.h"
bool
diff_chunk_context_empty(const struct diff_chunk_context *cc)
{
return diff_range_empty(&cc->chunk);
}
int
diff_chunk_get_left_start(const struct diff_chunk *c,
const struct diff_result *r, int context_lines)
{
int left_start = diff_atom_root_idx(r->left, c->left_start);
return MAX(0, left_start - context_lines);
}
int
diff_chunk_get_left_end(const struct diff_chunk *c,
const struct diff_result *r, int context_lines)
{
int left_start = diff_chunk_get_left_start(c, r, 0);
return MIN(r->left->atoms.len,
left_start + c->left_count + context_lines);
}
int
diff_chunk_get_right_start(const struct diff_chunk *c,
const struct diff_result *r, int context_lines)
{
int right_start = diff_atom_root_idx(r->right, c->right_start);
return MAX(0, right_start - context_lines);
}
int
diff_chunk_get_right_end(const struct diff_chunk *c,
const struct diff_result *r, int context_lines)
{
int right_start = diff_chunk_get_right_start(c, r, 0);
return MIN(r->right->atoms.len,
right_start + c->right_count + context_lines);
}
struct diff_chunk *
diff_chunk_get(const struct diff_result *r, int chunk_idx)
{
return &r->chunks.head[chunk_idx];
}
int
diff_chunk_get_left_count(struct diff_chunk *c)
{
return c->left_count;
}
int
diff_chunk_get_right_count(struct diff_chunk *c)
{
return c->right_count;
}
void
diff_chunk_context_get(struct diff_chunk_context *cc, const struct diff_result *r,
int chunk_idx, int context_lines)
{
const struct diff_chunk *c = &r->chunks.head[chunk_idx];
int left_start = diff_chunk_get_left_start(c, r, context_lines);
int left_end = diff_chunk_get_left_end(c, r, context_lines);
int right_start = diff_chunk_get_right_start(c, r, context_lines);
int right_end = diff_chunk_get_right_end(c, r, context_lines);
*cc = (struct diff_chunk_context){
.chunk = {
.start = chunk_idx,
.end = chunk_idx + 1,
},
.left = {
.start = left_start,
.end = left_end,
},
.right = {
.start = right_start,
.end = right_end,
},
};
}
bool
diff_chunk_contexts_touch(const struct diff_chunk_context *cc,
const struct diff_chunk_context *other)
{
return diff_ranges_touch(&cc->chunk, &other->chunk)
|| diff_ranges_touch(&cc->left, &other->left)
|| diff_ranges_touch(&cc->right, &other->right);
}
void
diff_chunk_contexts_merge(struct diff_chunk_context *cc,
const struct diff_chunk_context *other)
{
diff_ranges_merge(&cc->chunk, &other->chunk);
diff_ranges_merge(&cc->left, &other->left);
diff_ranges_merge(&cc->right, &other->right);
}
void
diff_chunk_context_load_change(struct diff_chunk_context *cc,
int *nchunks_used,
struct diff_result *result,
int start_chunk_idx,
int context_lines)
{
int i;
int seen_minus = 0, seen_plus = 0;
if (nchunks_used)
*nchunks_used = 0;
for (i = start_chunk_idx; i < result->chunks.len; i++) {
struct diff_chunk *chunk = &result->chunks.head[i];
enum diff_chunk_type t = diff_chunk_type(chunk);
struct diff_chunk_context next;
if (t != CHUNK_MINUS && t != CHUNK_PLUS) {
if (nchunks_used)
(*nchunks_used)++;
if (seen_minus || seen_plus)
break;
else
continue;
} else if (t == CHUNK_MINUS)
seen_minus = 1;
else if (t == CHUNK_PLUS)
seen_plus = 1;
if (diff_chunk_context_empty(cc)) {
/* Note down the start point, any number of subsequent
* chunks may be joined up to this chunk by being
* directly adjacent. */
diff_chunk_context_get(cc, result, i, context_lines);
if (nchunks_used)
(*nchunks_used)++;
continue;
}
/* There already is a previous chunk noted down for being
* printed. Does it join up with this one? */
diff_chunk_context_get(&next, result, i, context_lines);
if (diff_chunk_contexts_touch(cc, &next)) {
/* This next context touches or overlaps the previous
* one, join. */
diff_chunk_contexts_merge(cc, &next);
if (nchunks_used)
(*nchunks_used)++;
continue;
} else
break;
}
}
struct diff_output_unidiff_state {
bool header_printed;
char prototype[DIFF_FUNCTION_CONTEXT_SIZE];
int last_prototype_idx;
};
struct diff_output_unidiff_state *
diff_output_unidiff_state_alloc(void)
{
struct diff_output_unidiff_state *state;
state = calloc(1, sizeof(struct diff_output_unidiff_state));
if (state != NULL)
diff_output_unidiff_state_reset(state);
return state;
}
void
diff_output_unidiff_state_reset(struct diff_output_unidiff_state *state)
{
state->header_printed = false;
memset(state->prototype, 0, sizeof(state->prototype));
state->last_prototype_idx = 0;
}
void
diff_output_unidiff_state_free(struct diff_output_unidiff_state *state)
{
free(state);
}
static int
output_unidiff_chunk(struct diff_output_info *outinfo, FILE *dest,
struct diff_output_unidiff_state *state,
const struct diff_input_info *info,
const struct diff_result *result,
bool print_header, bool show_function_prototypes,
const struct diff_chunk_context *cc)
{
int rc, left_start, left_len, right_start, right_len;
off_t outoff = 0, *offp;
if (diff_range_empty(&cc->left) && diff_range_empty(&cc->right))
return DIFF_RC_OK;
if (outinfo && outinfo->line_offsets.len > 0) {
unsigned int idx = outinfo->line_offsets.len - 1;
outoff = outinfo->line_offsets.head[idx];
}
if (print_header && !(state->header_printed)) {
rc = fprintf(dest, "--- %s\n",
diff_output_get_label_left(info));
if (rc < 0)
return errno;
if (outinfo) {
ARRAYLIST_ADD(offp, outinfo->line_offsets);
if (offp == NULL)
return ENOMEM;
outoff += rc;
*offp = outoff;
}
rc = fprintf(dest, "+++ %s\n",
diff_output_get_label_right(info));
if (rc < 0)
return errno;
if (outinfo) {
ARRAYLIST_ADD(offp, outinfo->line_offsets);
if (offp == NULL)
return ENOMEM;
outoff += rc;
*offp = outoff;
}
state->header_printed = true;
}
left_len = cc->left.end - cc->left.start;
if (result->left->atoms.len == 0)
left_start = 0;
else if (left_len == 0 && cc->left.start > 0)
left_start = cc->left.start;
else
left_start = cc->left.start + 1;
right_len = cc->right.end - cc->right.start;
if (result->right->atoms.len == 0)
right_start = 0;
else if (right_len == 0 && cc->right.start > 0)
right_start = cc->right.start;
else
right_start = cc->right.start + 1;
if (show_function_prototypes) {
rc = diff_output_match_function_prototype(state->prototype,
sizeof(state->prototype), &state->last_prototype_idx,
result, cc);
if (rc)
return rc;
}
if (left_len == 1 && right_len == 1) {
rc = fprintf(dest, "@@ -%d +%d @@%s%s\n",
left_start, right_start,
state->prototype[0] ? " " : "",
state->prototype[0] ? state->prototype : "");
} else if (left_len == 1 && right_len != 1) {
rc = fprintf(dest, "@@ -%d +%d,%d @@%s%s\n",
left_start, right_start, right_len,
state->prototype[0] ? " " : "",
state->prototype[0] ? state->prototype : "");
} else if (left_len != 1 && right_len == 1) {
rc = fprintf(dest, "@@ -%d,%d +%d @@%s%s\n",
left_start, left_len, right_start,
state->prototype[0] ? " " : "",
state->prototype[0] ? state->prototype : "");
} else {
rc = fprintf(dest, "@@ -%d,%d +%d,%d @@%s%s\n",
left_start, left_len, right_start, right_len,
state->prototype[0] ? " " : "",
state->prototype[0] ? state->prototype : "");
}
if (rc < 0)
return errno;
if (outinfo) {
ARRAYLIST_ADD(offp, outinfo->line_offsets);
if (offp == NULL)
return ENOMEM;
outoff += rc;
*offp = outoff;
}
/* Got the absolute line numbers where to start printing, and the index
* of the interesting (non-context) chunk.
* To print context lines above the interesting chunk, nipping on the
* previous chunk index may be necessary.
* It is guaranteed to be only context lines where left == right, so it
* suffices to look on the left. */
const struct diff_chunk *first_chunk;
int chunk_start_line;
first_chunk = &result->chunks.head[cc->chunk.start];
chunk_start_line = diff_atom_root_idx(result->left,
first_chunk->left_start);
if (cc->left.start < chunk_start_line) {
rc = diff_output_lines(outinfo, dest, " ",
&result->left->atoms.head[cc->left.start],
chunk_start_line - cc->left.start);
if (rc)
return rc;
}
/* Now write out all the joined chunks and contexts between them */
int c_idx;
for (c_idx = cc->chunk.start; c_idx < cc->chunk.end; c_idx++) {
const struct diff_chunk *c = &result->chunks.head[c_idx];
if (c->left_count && c->right_count)
rc = diff_output_lines(outinfo, dest,
c->solved ? " " : "?",
c->left_start, c->left_count);
else if (c->left_count && !c->right_count)
rc = diff_output_lines(outinfo, dest,
c->solved ? "-" : "?",
c->left_start, c->left_count);
else if (c->right_count && !c->left_count)
rc = diff_output_lines(outinfo, dest,
c->solved ? "+" : "?",
c->right_start, c->right_count);
if (rc)
return rc;
if (cc->chunk.end == result->chunks.len) {
rc = diff_output_trailing_newline_msg(outinfo, dest, c);
if (rc != DIFF_RC_OK)
return rc;
}
}
/* Trailing context? */
const struct diff_chunk *last_chunk;
int chunk_end_line;
last_chunk = &result->chunks.head[cc->chunk.end - 1];
chunk_end_line = diff_atom_root_idx(result->left,
last_chunk->left_start
+ last_chunk->left_count);
if (cc->left.end > chunk_end_line) {
rc = diff_output_lines(outinfo, dest, " ",
&result->left->atoms.head[chunk_end_line],
cc->left.end - chunk_end_line);
if (rc)
return rc;
}
return DIFF_RC_OK;
}
int
diff_output_unidiff_chunk(struct diff_output_info **output_info, FILE *dest,
struct diff_output_unidiff_state *state,
const struct diff_input_info *info,
const struct diff_result *result,
const struct diff_chunk_context *cc)
{
struct diff_output_info *outinfo = NULL;
int flags = (result->left->root->diff_flags |
result->right->root->diff_flags);
bool show_function_prototypes = (flags & DIFF_FLAG_SHOW_PROTOTYPES);
if (output_info) {
*output_info = diff_output_info_alloc();
if (*output_info == NULL)
return ENOMEM;
outinfo = *output_info;
}
return output_unidiff_chunk(outinfo, dest, state, info,
result, false, show_function_prototypes, cc);
}
int
diff_output_unidiff(struct diff_output_info **output_info,
FILE *dest, const struct diff_input_info *info,
const struct diff_result *result,
unsigned int context_lines)
{
struct diff_output_unidiff_state *state;
struct diff_chunk_context cc = {};
struct diff_output_info *outinfo = NULL;
int atomizer_flags = (result->left->atomizer_flags|
result->right->atomizer_flags);
int flags = (result->left->root->diff_flags |
result->right->root->diff_flags);
bool show_function_prototypes = (flags & DIFF_FLAG_SHOW_PROTOTYPES);
bool force_text = (flags & DIFF_FLAG_FORCE_TEXT_DATA);
bool have_binary = (atomizer_flags & DIFF_ATOMIZER_FOUND_BINARY_DATA);
int i;
if (!result)
return EINVAL;
if (result->rc != DIFF_RC_OK)
return result->rc;
if (output_info) {
*output_info = diff_output_info_alloc();
if (*output_info == NULL)
return ENOMEM;
outinfo = *output_info;
}
if (have_binary && !force_text) {
for (i = 0; i < result->chunks.len; i++) {
struct diff_chunk *c = &result->chunks.head[i];
enum diff_chunk_type t = diff_chunk_type(c);
if (t != CHUNK_MINUS && t != CHUNK_PLUS)
continue;
fprintf(dest, "Binary files %s and %s differ\n",
diff_output_get_label_left(info),
diff_output_get_label_right(info));
break;
}
return DIFF_RC_OK;
}
state = diff_output_unidiff_state_alloc();
if (state == NULL) {
if (output_info) {
diff_output_info_free(*output_info);
*output_info = NULL;
}
return ENOMEM;
}
#if DEBUG
unsigned int check_left_pos, check_right_pos;
check_left_pos = 0;
check_right_pos = 0;
for (i = 0; i < result->chunks.len; i++) {
struct diff_chunk *c = &result->chunks.head[i];
enum diff_chunk_type t = diff_chunk_type(c);
debug("[%d] %s lines L%d R%d @L %d @R %d\n",
i, (t == CHUNK_MINUS ? "minus" :
(t == CHUNK_PLUS ? "plus" :
(t == CHUNK_SAME ? "same" : "?"))),
c->left_count,
c->right_count,
c->left_start ? diff_atom_root_idx(result->left, c->left_start) : -1,
c->right_start ? diff_atom_root_idx(result->right, c->right_start) : -1);
assert(check_left_pos == diff_atom_root_idx(result->left, c->left_start));
assert(check_right_pos == diff_atom_root_idx(result->right, c->right_start));
check_left_pos += c->left_count;
check_right_pos += c->right_count;
}
assert(check_left_pos == result->left->atoms.len);
assert(check_right_pos == result->right->atoms.len);
#endif
for (i = 0; i < result->chunks.len; i++) {
struct diff_chunk *c = &result->chunks.head[i];
enum diff_chunk_type t = diff_chunk_type(c);
struct diff_chunk_context next;
if (t != CHUNK_MINUS && t != CHUNK_PLUS)
continue;
if (diff_chunk_context_empty(&cc)) {
/* These are the first lines being printed.
* Note down the start point, any number of subsequent
* chunks may be joined up to this unidiff chunk by
* context lines or by being directly adjacent. */
diff_chunk_context_get(&cc, result, i, context_lines);
debug("new chunk to be printed:"
" chunk %d-%d left %d-%d right %d-%d\n",
cc.chunk.start, cc.chunk.end,
cc.left.start, cc.left.end,
cc.right.start, cc.right.end);
continue;
}
/* There already is a previous chunk noted down for being
* printed. Does it join up with this one? */
diff_chunk_context_get(&next, result, i, context_lines);
debug("new chunk to be printed:"
" chunk %d-%d left %d-%d right %d-%d\n",
next.chunk.start, next.chunk.end,
next.left.start, next.left.end,
next.right.start, next.right.end);
if (diff_chunk_contexts_touch(&cc, &next)) {
/* This next context touches or overlaps the previous
* one, join. */
diff_chunk_contexts_merge(&cc, &next);
debug("new chunk to be printed touches previous chunk,"
" now: left %d-%d right %d-%d\n",
cc.left.start, cc.left.end,
cc.right.start, cc.right.end);
continue;
}
/* No touching, so the previous context is complete with a gap
* between it and this next one. Print the previous one and
* start fresh here. */
debug("new chunk to be printed does not touch previous chunk;"
" print left %d-%d right %d-%d\n",
cc.left.start, cc.left.end, cc.right.start, cc.right.end);
output_unidiff_chunk(outinfo, dest, state, info, result,
true, show_function_prototypes, &cc);
cc = next;
debug("new unprinted chunk is left %d-%d right %d-%d\n",
cc.left.start, cc.left.end, cc.right.start, cc.right.end);
}
if (!diff_chunk_context_empty(&cc))
output_unidiff_chunk(outinfo, dest, state, info, result,
true, show_function_prototypes, &cc);
diff_output_unidiff_state_free(state);
return DIFF_RC_OK;
}
|
ThomasAdam/gameoftrees
|
libexec/got-fetch-pack/got-fetch-pack.c
|
/*
* Copyright (c) 2019 <NAME> <<EMAIL>>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <stdint.h>
#include <errno.h>
#include <limits.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sha1.h>
#include <fcntl.h>
#include <unistd.h>
#include <zlib.h>
#include <err.h>
#include "got_compat.h"
#include "got_error.h"
#include "got_object.h"
#include "got_path.h"
#include "got_version.h"
#include "got_fetch.h"
#include "got_reference.h"
#include "got_lib_sha1.h"
#include "got_lib_delta.h"
#include "got_lib_object.h"
#include "got_lib_object_parse.h"
#include "got_lib_privsep.h"
#include "got_lib_pack.h"
#ifndef nitems
#define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
#endif
struct got_object *indexed;
static int chattygot;
static struct got_object_id zhash = {.sha1={0}};
static const struct got_error *
readn(ssize_t *off, int fd, void *buf, size_t n)
{
ssize_t r;
*off = 0;
while (*off != n) {
r = read(fd, buf + *off, n - *off);
if (r == -1)
return got_error_from_errno("read");
if (r == 0)
return NULL;
*off += r;
}
return NULL;
}
static const struct got_error *
flushpkt(int fd)
{
ssize_t w;
if (chattygot > 1)
fprintf(stderr, "%s: writepkt: 0000\n", getprogname());
w = write(fd, "0000", 4);
if (w == -1)
return got_error_from_errno("write");
if (w != 4)
return got_error(GOT_ERR_IO);
return NULL;
}
/*
* Packet header contains a 4-byte hexstring which specifies the length
* of data which follows.
*/
static const struct got_error *
read_pkthdr(int *datalen, int fd)
{
static const struct got_error *err = NULL;
char lenstr[5];
long len;
char *e;
int n, i;
ssize_t r;
*datalen = 0;
err = readn(&r, fd, lenstr, 4);
if (err)
return err;
if (r == 0) {
/* implicit "0000" */
if (chattygot > 1)
fprintf(stderr, "%s: readpkt: 0000\n", getprogname());
return NULL;
}
if (r != 4)
return got_error_msg(GOT_ERR_BAD_PACKET,
"wrong packet header length");
lenstr[4] = '\0';
for (i = 0; i < 4; i++) {
if (!isprint((unsigned char)lenstr[i]))
return got_error_msg(GOT_ERR_BAD_PACKET,
"unprintable character in packet length field");
}
for (i = 0; i < 4; i++) {
if (!isxdigit((unsigned char)lenstr[i])) {
if (chattygot)
fprintf(stderr, "%s: bad length: '%s'\n",
getprogname(), lenstr);
return got_error_msg(GOT_ERR_BAD_PACKET,
"packet length not specified in hex");
}
}
errno = 0;
len = strtol(lenstr, &e, 16);
if (lenstr[0] == '\0' || *e != '\0')
return got_error(GOT_ERR_BAD_PACKET);
if (errno == ERANGE && (len == LONG_MAX || len == LONG_MIN))
return got_error_msg(GOT_ERR_BAD_PACKET, "bad packet length");
if (len > INT_MAX || len < INT_MIN)
return got_error_msg(GOT_ERR_BAD_PACKET, "bad packet length");
n = len;
if (n == 0)
return NULL;
if (n <= 4)
return got_error_msg(GOT_ERR_BAD_PACKET, "packet too short");
n -= 4;
*datalen = n;
return NULL;
}
static const struct got_error *
readpkt(int *outlen, int fd, char *buf, int buflen)
{
const struct got_error *err = NULL;
int datalen, i;
ssize_t n;
err = read_pkthdr(&datalen, fd);
if (err)
return err;
if (datalen > buflen)
return got_error(GOT_ERR_NO_SPACE);
err = readn(&n, fd, buf, datalen);
if (err)
return err;
if (n != datalen)
return got_error_msg(GOT_ERR_BAD_PACKET, "short packet");
if (chattygot > 1) {
fprintf(stderr, "%s: readpkt: %zd:\t", getprogname(), n);
for (i = 0; i < n; i++) {
if (isprint(buf[i]))
fputc(buf[i], stderr);
else
fprintf(stderr, "[0x%.2x]", buf[i]);
}
fputc('\n', stderr);
}
*outlen = n;
return NULL;
}
static const struct got_error *
writepkt(int fd, char *buf, int nbuf)
{
char len[5];
int i;
ssize_t w;
if (snprintf(len, sizeof(len), "%04x", nbuf + 4) >= sizeof(len))
return got_error(GOT_ERR_NO_SPACE);
w = write(fd, len, 4);
if (w == -1)
return got_error_from_errno("write");
if (w != 4)
return got_error(GOT_ERR_IO);
w = write(fd, buf, nbuf);
if (w == -1)
return got_error_from_errno("write");
if (w != nbuf)
return got_error(GOT_ERR_IO);
if (chattygot > 1) {
fprintf(stderr, "%s: writepkt: %s:\t", getprogname(), len);
for (i = 0; i < nbuf; i++) {
if (isprint(buf[i]))
fputc(buf[i], stderr);
else
fprintf(stderr, "[0x%.2x]", buf[i]);
}
fputc('\n', stderr);
}
return NULL;
}
static void
match_remote_ref(struct got_pathlist_head *have_refs,
struct got_object_id *my_id, char *refname)
{
struct got_pathlist_entry *pe;
/* XXX zero-hash signifies we don't have this ref;
* we should use a flag instead */
memset(my_id, 0, sizeof(*my_id));
TAILQ_FOREACH(pe, have_refs, entry) {
struct got_object_id *id = pe->data;
if (strcmp(pe->path, refname) == 0) {
memcpy(my_id, id, sizeof(*my_id));
break;
}
}
}
static int
match_branch(const char *branch, const char *wanted_branch)
{
if (strncmp(branch, "refs/heads/", 11) != 0)
return 0;
if (strncmp(wanted_branch, "refs/heads/", 11) == 0)
wanted_branch += 11;
return (strcmp(branch + 11, wanted_branch) == 0);
}
static int
match_wanted_ref(const char *refname, const char *wanted_ref)
{
if (strncmp(refname, "refs/", 5) != 0)
return 0;
refname += 5;
/*
* Prevent fetching of references that won't make any
* sense outside of the remote repository's context.
*/
if (strncmp(refname, "got/", 4) == 0)
return 0;
if (strncmp(refname, "remotes/", 8) == 0)
return 0;
if (strncmp(wanted_ref, "refs/", 5) == 0)
wanted_ref += 5;
/* Allow prefix match. */
if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
return 1;
/* Allow exact match. */
return (strcmp(refname, wanted_ref) == 0);
}
static const struct got_error *
tokenize_refline(char **tokens, char *line, int len, int maxtokens)
{
const struct got_error *err = NULL;
char *p;
size_t i, n = 0;
for (i = 0; i < maxtokens; i++)
tokens[i] = NULL;
for (i = 0; n < len && i < maxtokens; i++) {
while (isspace(*line)) {
line++;
n++;
}
p = line;
while (*line != '\0' &&
(!isspace(*line) || i == maxtokens - 1)) {
line++;
n++;
}
tokens[i] = strndup(p, line - p);
if (tokens[i] == NULL) {
err = got_error_from_errno("strndup");
goto done;
}
/* Skip \0 field-delimiter at end of token. */
while (line[0] == '\0' && n < len) {
line++;
n++;
}
}
if (i <= 2)
err = got_error(GOT_ERR_NOT_REF);
done:
if (err) {
int j;
for (j = 0; j < i; j++) {
free(tokens[j]);
tokens[j] = NULL;
}
}
return err;
}
static const struct got_error *
parse_refline(char **id_str, char **refname, char **server_capabilities,
char *line, int len)
{
const struct got_error *err = NULL;
char *tokens[3];
err = tokenize_refline(tokens, line, len, nitems(tokens));
if (err)
return err;
if (tokens[0])
*id_str = tokens[0];
if (tokens[1])
*refname = tokens[1];
if (tokens[2]) {
char *p;
*server_capabilities = tokens[2];
p = strrchr(*server_capabilities, '\n');
if (p)
*p = '\0';
}
return NULL;
}
#define GOT_CAPA_AGENT "agent"
#define GOT_CAPA_OFS_DELTA "ofs-delta"
#define GOT_CAPA_SIDE_BAND_64K "side-band-64k"
#define GOT_SIDEBAND_PACKFILE_DATA 1
#define GOT_SIDEBAND_PROGRESS_INFO 2
#define GOT_SIDEBAND_ERROR_INFO 3
struct got_capability {
const char *key;
const char *value;
};
static const struct got_capability got_capabilities[] = {
{ GOT_CAPA_AGENT, "got/" GOT_VERSION_STR },
{ GOT_CAPA_OFS_DELTA, NULL },
{ GOT_CAPA_SIDE_BAND_64K, NULL },
};
static const struct got_error *
match_capability(char **my_capabilities, const char *capa,
const struct got_capability *mycapa)
{
char *equalsign;
char *s;
equalsign = strchr(capa, '=');
if (equalsign) {
if (strncmp(capa, mycapa->key, equalsign - capa) != 0)
return NULL;
} else {
if (strcmp(capa, mycapa->key) != 0)
return NULL;
}
if (asprintf(&s, "%s %s%s%s",
*my_capabilities != NULL ? *my_capabilities : "",
mycapa->key,
mycapa->value != NULL ? "=" : "",
mycapa->value != NULL? mycapa->value : "") == -1)
return got_error_from_errno("asprintf");
free(*my_capabilities);
*my_capabilities = s;
return NULL;
}
static const struct got_error *
add_symref(struct got_pathlist_head *symrefs, char *capa)
{
const struct got_error *err = NULL;
char *colon, *name = NULL, *target = NULL;
/* Need at least "A:B" */
if (strlen(capa) < 3)
return NULL;
colon = strchr(capa, ':');
if (colon == NULL)
return NULL;
*colon = '\0';
name = strdup(capa);
if (name == NULL)
return got_error_from_errno("strdup");
target = strdup(colon + 1);
if (target == NULL) {
err = got_error_from_errno("strdup");
goto done;
}
/* We can't validate the ref itself here. The main process will. */
err = got_pathlist_append(symrefs, name, target);
done:
if (err) {
free(name);
free(target);
}
return err;
}
static const struct got_error *
match_capabilities(char **my_capabilities, struct got_pathlist_head *symrefs,
char *server_capabilities)
{
const struct got_error *err = NULL;
char *capa, *equalsign;
size_t i;
*my_capabilities = NULL;
do {
capa = strsep(&server_capabilities, " ");
if (capa == NULL)
return NULL;
equalsign = strchr(capa, '=');
if (equalsign != NULL &&
strncmp(capa, "symref", equalsign - capa) == 0) {
err = add_symref(symrefs, equalsign + 1);
if (err)
break;
continue;
}
for (i = 0; i < nitems(got_capabilities); i++) {
err = match_capability(my_capabilities,
capa, &got_capabilities[i]);
if (err)
break;
}
} while (capa);
if (*my_capabilities == NULL) {
*my_capabilities = strdup("");
if (*my_capabilities == NULL)
err = got_error_from_errno("strdup");
}
return err;
}
static const struct got_error *
send_fetch_server_progress(struct imsgbuf *ibuf, const char *msg, size_t msglen)
{
if (msglen > MAX_IMSGSIZE - IMSG_HEADER_SIZE)
return got_error(GOT_ERR_NO_SPACE);
if (msglen == 0)
return NULL;
if (imsg_compose(ibuf, GOT_IMSG_FETCH_SERVER_PROGRESS, 0, 0, -1,
msg, msglen) == -1)
return got_error_from_errno(
"imsg_compose FETCH_SERVER_PROGRESS");
return got_privsep_flush_imsg(ibuf);
}
static const struct got_error *
send_fetch_download_progress(struct imsgbuf *ibuf, off_t bytes)
{
if (imsg_compose(ibuf, GOT_IMSG_FETCH_DOWNLOAD_PROGRESS, 0, 0, -1,
&bytes, sizeof(bytes)) == -1)
return got_error_from_errno(
"imsg_compose FETCH_DOWNLOAD_PROGRESS");
return got_privsep_flush_imsg(ibuf);
}
static const struct got_error *
send_fetch_done(struct imsgbuf *ibuf, uint8_t *pack_sha1)
{
if (imsg_compose(ibuf, GOT_IMSG_FETCH_DONE, 0, 0, -1,
pack_sha1, SHA1_DIGEST_LENGTH) == -1)
return got_error_from_errno("imsg_compose FETCH");
return got_privsep_flush_imsg(ibuf);
}
static const struct got_error *
fetch_progress(struct imsgbuf *ibuf, const char *buf, size_t len)
{
size_t i;
if (len == 0)
return NULL;
/*
* Truncate messages which exceed the maximum imsg payload size.
* Server may send up to 64k.
*/
if (len > MAX_IMSGSIZE - IMSG_HEADER_SIZE)
len = MAX_IMSGSIZE - IMSG_HEADER_SIZE;
/* Only allow printable ASCII. */
for (i = 0; i < len; i++) {
if (isprint((unsigned char)buf[i]) ||
isspace((unsigned char)buf[i]))
continue;
return got_error_msg(GOT_ERR_BAD_PACKET,
"non-printable progress message received from server");
}
return send_fetch_server_progress(ibuf, buf, len);
}
static const struct got_error *
fetch_error(const char *buf, size_t len)
{
static char msg[1024];
size_t i;
for (i = 0; i < len && i < sizeof(msg) - 1; i++) {
if (!isprint(buf[i]))
return got_error_msg(GOT_ERR_BAD_PACKET,
"non-printable error message received from server");
msg[i] = buf[i];
}
msg[i] = '\0';
return got_error_msg(GOT_ERR_FETCH_FAILED, msg);
}
static const struct got_error *
send_fetch_symrefs(struct imsgbuf *ibuf, struct got_pathlist_head *symrefs)
{
const struct got_error *err = NULL;
struct ibuf *wbuf;
size_t len, nsymrefs = 0;
struct got_pathlist_entry *pe;
len = sizeof(struct got_imsg_fetch_symrefs);
TAILQ_FOREACH(pe, symrefs, entry) {
const char *target = pe->data;
len += sizeof(struct got_imsg_fetch_symref) +
pe->path_len + strlen(target);
nsymrefs++;
}
if (len >= MAX_IMSGSIZE - IMSG_HEADER_SIZE)
return got_error(GOT_ERR_NO_SPACE);
wbuf = imsg_create(ibuf, GOT_IMSG_FETCH_SYMREFS, 0, 0, len);
if (wbuf == NULL)
return got_error_from_errno("imsg_create FETCH_SYMREFS");
/* Keep in sync with struct got_imsg_fetch_symrefs definition! */
if (imsg_add(wbuf, &nsymrefs, sizeof(nsymrefs)) == -1) {
err = got_error_from_errno("imsg_add FETCH_SYMREFS");
ibuf_free(wbuf);
return err;
}
TAILQ_FOREACH(pe, symrefs, entry) {
const char *name = pe->path;
size_t name_len = pe->path_len;
const char *target = pe->data;
size_t target_len = strlen(target);
/* Keep in sync with struct got_imsg_fetch_symref definition! */
if (imsg_add(wbuf, &name_len, sizeof(name_len)) == -1) {
err = got_error_from_errno("imsg_add FETCH_SYMREFS");
ibuf_free(wbuf);
return err;
}
if (imsg_add(wbuf, &target_len, sizeof(target_len)) == -1) {
err = got_error_from_errno("imsg_add FETCH_SYMREFS");
ibuf_free(wbuf);
return err;
}
if (imsg_add(wbuf, name, name_len) == -1) {
err = got_error_from_errno("imsg_add FETCH_SYMREFS");
ibuf_free(wbuf);
return err;
}
if (imsg_add(wbuf, target, target_len) == -1) {
err = got_error_from_errno("imsg_add FETCH_SYMREFS");
ibuf_free(wbuf);
return err;
}
}
wbuf->fd = -1;
imsg_close(ibuf, wbuf);
return got_privsep_flush_imsg(ibuf);
}
static const struct got_error *
send_fetch_ref(struct imsgbuf *ibuf, struct got_object_id *refid,
const char *refname)
{
const struct got_error *err = NULL;
struct ibuf *wbuf;
size_t len, reflen = strlen(refname);
len = sizeof(struct got_imsg_fetch_ref) + reflen;
if (len >= MAX_IMSGSIZE - IMSG_HEADER_SIZE)
return got_error(GOT_ERR_NO_SPACE);
wbuf = imsg_create(ibuf, GOT_IMSG_FETCH_REF, 0, 0, len);
if (wbuf == NULL)
return got_error_from_errno("imsg_create FETCH_REF");
/* Keep in sync with struct got_imsg_fetch_ref definition! */
if (imsg_add(wbuf, refid->sha1, SHA1_DIGEST_LENGTH) == -1) {
err = got_error_from_errno("imsg_add FETCH_REF");
ibuf_free(wbuf);
return err;
}
if (imsg_add(wbuf, refname, reflen) == -1) {
err = got_error_from_errno("imsg_add FETCH_REF");
ibuf_free(wbuf);
return err;
}
wbuf->fd = -1;
imsg_close(ibuf, wbuf);
return got_privsep_flush_imsg(ibuf);
}
static const struct got_error *
fetch_pack(int fd, int packfd, uint8_t *pack_sha1,
struct got_pathlist_head *have_refs, int fetch_all_branches,
struct got_pathlist_head *wanted_branches,
struct got_pathlist_head *wanted_refs, int list_refs_only,
struct imsgbuf *ibuf)
{
const struct got_error *err = NULL;
char buf[GOT_FETCH_PKTMAX];
char hashstr[SHA1_DIGEST_STRING_LENGTH];
struct got_object_id *have, *want;
int is_firstpkt = 1, nref = 0, refsz = 16;
int i, n, nwant = 0, nhave = 0, acked = 0;
off_t packsz = 0, last_reported_packsz = 0;
char *id_str = NULL, *refname = NULL;
char *server_capabilities = NULL, *my_capabilities = NULL;
const char *default_branch = NULL;
struct got_pathlist_head symrefs;
struct got_pathlist_entry *pe;
int sent_my_capabilites = 0, have_sidebands = 0;
int found_branch = 0;
SHA1_CTX sha1_ctx;
uint8_t sha1_buf[SHA1_DIGEST_LENGTH];
size_t sha1_buf_len = 0;
ssize_t w;
TAILQ_INIT(&symrefs);
SHA1Init(&sha1_ctx);
have = malloc(refsz * sizeof(have[0]));
if (have == NULL)
return got_error_from_errno("malloc");
want = malloc(refsz * sizeof(want[0]));
if (want == NULL) {
err = got_error_from_errno("malloc");
goto done;
}
while (1) {
err = readpkt(&n, fd, buf, sizeof(buf));
if (err)
goto done;
if (n == 0)
break;
if (n >= 4 && strncmp(buf, "ERR ", 4) == 0) {
err = fetch_error(&buf[4], n - 4);
goto done;
}
err = parse_refline(&id_str, &refname, &server_capabilities,
buf, n);
if (err)
goto done;
if (is_firstpkt) {
if (chattygot && server_capabilities[0] != '\0')
fprintf(stderr, "%s: server capabilities: %s\n",
getprogname(), server_capabilities);
err = match_capabilities(&my_capabilities, &symrefs,
server_capabilities);
if (err)
goto done;
if (chattygot)
fprintf(stderr, "%s: my capabilities:%s\n",
getprogname(), my_capabilities);
err = send_fetch_symrefs(ibuf, &symrefs);
if (err)
goto done;
is_firstpkt = 0;
if (!fetch_all_branches) {
TAILQ_FOREACH(pe, &symrefs, entry) {
const char *name = pe->path;
const char *symref_target = pe->data;
if (strcmp(name, GOT_REF_HEAD) != 0)
continue;
default_branch = symref_target;
break;
}
}
continue;
}
if (strstr(refname, "^{}")) {
if (chattygot) {
fprintf(stderr, "%s: ignoring %s\n",
getprogname(), refname);
}
continue;
}
if (strncmp(refname, "refs/heads/", 11) == 0) {
if (fetch_all_branches || list_refs_only) {
found_branch = 1;
} else if (!TAILQ_EMPTY(wanted_branches)) {
TAILQ_FOREACH(pe, wanted_branches, entry) {
if (match_branch(refname, pe->path))
break;
}
if (pe == NULL) {
if (chattygot) {
fprintf(stderr,
"%s: ignoring %s\n",
getprogname(), refname);
}
continue;
}
found_branch = 1;
} else if (default_branch != NULL) {
if (!match_branch(refname, default_branch)) {
if (chattygot) {
fprintf(stderr,
"%s: ignoring %s\n",
getprogname(), refname);
}
continue;
}
found_branch = 1;
}
} else if (strncmp(refname, "refs/tags/", 10) != 0) {
if (!TAILQ_EMPTY(wanted_refs)) {
TAILQ_FOREACH(pe, wanted_refs, entry) {
if (match_wanted_ref(refname, pe->path))
break;
}
if (pe == NULL) {
if (chattygot) {
fprintf(stderr,
"%s: ignoring %s\n",
getprogname(), refname);
}
continue;
}
found_branch = 1;
} else if (!list_refs_only) {
if (chattygot) {
fprintf(stderr, "%s: ignoring %s\n",
getprogname(), refname);
}
continue;
}
}
if (refsz == nref + 1) {
refsz *= 2;
have = reallocarray(have, refsz, sizeof(have[0]));
if (have == NULL) {
err = got_error_from_errno("reallocarray");
goto done;
}
want = reallocarray(want, refsz, sizeof(want[0]));
if (want == NULL) {
err = got_error_from_errno("reallocarray");
goto done;
}
}
if (!got_parse_sha1_digest(want[nref].sha1, id_str)) {
err = got_error(GOT_ERR_BAD_OBJ_ID_STR);
goto done;
}
match_remote_ref(have_refs, &have[nref], refname);
err = send_fetch_ref(ibuf, &want[nref], refname);
if (err)
goto done;
if (chattygot)
fprintf(stderr, "%s: %s will be fetched\n",
getprogname(), refname);
if (chattygot > 1) {
char *theirs, *mine;
err = got_object_id_str(&theirs, &want[nref]);
if (err)
goto done;
err = got_object_id_str(&mine, &have[nref]);
if (err) {
free(theirs);
goto done;
}
fprintf(stderr, "%s: remote: %s\n%s: local: %s\n",
getprogname(), theirs, getprogname(), mine);
free(theirs);
free(mine);
}
nref++;
}
if (list_refs_only)
goto done;
/* Abort if we haven't found any branch to fetch. */
if (!found_branch) {
err = got_error(GOT_ERR_FETCH_NO_BRANCH);
goto done;
}
for (i = 0; i < nref; i++) {
if (got_object_id_cmp(&have[i], &want[i]) == 0)
continue;
got_sha1_digest_to_str(want[i].sha1, hashstr, sizeof(hashstr));
n = snprintf(buf, sizeof(buf), "want %s%s\n", hashstr,
sent_my_capabilites ? "" : my_capabilities);
if (n >= sizeof(buf)) {
err = got_error(GOT_ERR_NO_SPACE);
goto done;
}
err = writepkt(fd, buf, n);
if (err)
goto done;
sent_my_capabilites = 1;
nwant++;
}
err = flushpkt(fd);
if (err)
goto done;
if (nwant == 0)
goto done;
for (i = 0; i < nref; i++) {
if (got_object_id_cmp(&have[i], &zhash) == 0)
continue;
got_sha1_digest_to_str(have[i].sha1, hashstr, sizeof(hashstr));
n = snprintf(buf, sizeof(buf), "have %s\n", hashstr);
if (n >= sizeof(buf)) {
err = got_error(GOT_ERR_NO_SPACE);
goto done;
}
err = writepkt(fd, buf, n);
if (err)
goto done;
nhave++;
}
while (nhave > 0 && !acked) {
struct got_object_id common_id;
/* The server should ACK the object IDs we need. */
err = readpkt(&n, fd, buf, sizeof(buf));
if (err)
goto done;
if (n >= 4 && strncmp(buf, "ERR ", 4) == 0) {
err = fetch_error(&buf[4], n - 4);
goto done;
}
if (n >= 4 && strncmp(buf, "NAK\n", 4) == 0) {
/* Server has not located our objects yet. */
continue;
}
if (n < 4 + SHA1_DIGEST_STRING_LENGTH ||
strncmp(buf, "ACK ", 4) != 0) {
err = got_error_msg(GOT_ERR_BAD_PACKET,
"unexpected message from server");
goto done;
}
if (!got_parse_sha1_digest(common_id.sha1, buf + 4)) {
err = got_error_msg(GOT_ERR_BAD_PACKET,
"bad object ID in ACK packet from server");
goto done;
}
acked++;
}
n = snprintf(buf, sizeof(buf), "done\n");
err = writepkt(fd, buf, n);
if (err)
goto done;
if (nhave == 0) {
err = readpkt(&n, fd, buf, sizeof(buf));
if (err)
goto done;
if (n != 4 || strncmp(buf, "NAK\n", n) != 0) {
err = got_error_msg(GOT_ERR_BAD_PACKET,
"unexpected message from server");
goto done;
}
}
if (chattygot)
fprintf(stderr, "%s: fetching...\n", getprogname());
if (my_capabilities != NULL &&
strstr(my_capabilities, GOT_CAPA_SIDE_BAND_64K) != NULL)
have_sidebands = 1;
while (1) {
ssize_t r = 0;
int datalen = -1;
if (have_sidebands) {
err = read_pkthdr(&datalen, fd);
if (err)
goto done;
if (datalen <= 0)
break;
/* Read sideband channel ID (one byte). */
r = read(fd, buf, 1);
if (r == -1) {
err = got_error_from_errno("read");
goto done;
}
if (r != 1) {
err = got_error_msg(GOT_ERR_BAD_PACKET,
"short packet");
goto done;
}
if (datalen > sizeof(buf) - 5) {
err = got_error_msg(GOT_ERR_BAD_PACKET,
"bad packet length");
goto done;
}
datalen--; /* sideband ID has been read */
if (buf[0] == GOT_SIDEBAND_PACKFILE_DATA) {
/* Read packfile data. */
err = readn(&r, fd, buf, datalen);
if (err)
goto done;
if (r != datalen) {
err = got_error_msg(GOT_ERR_BAD_PACKET,
"packet too short");
goto done;
}
} else if (buf[0] == GOT_SIDEBAND_PROGRESS_INFO) {
err = readn(&r, fd, buf, datalen);
if (err)
goto done;
if (r != datalen) {
err = got_error_msg(GOT_ERR_BAD_PACKET,
"packet too short");
goto done;
}
err = fetch_progress(ibuf, buf, r);
if (err)
goto done;
continue;
} else if (buf[0] == GOT_SIDEBAND_ERROR_INFO) {
err = readn(&r, fd, buf, datalen);
if (err)
goto done;
if (r != datalen) {
err = got_error_msg(GOT_ERR_BAD_PACKET,
"packet too short");
goto done;
}
err = fetch_error(buf, r);
goto done;
} else if (buf[0] == 'A') {
err = readn(&r, fd, buf, datalen);
if (err)
goto done;
if (r != datalen) {
err = got_error_msg(GOT_ERR_BAD_PACKET,
"packet too short");
goto done;
}
/*
* Git server responds with ACK after 'done'
* even though multi_ack is disabled?!?
*/
buf[r] = '\0';
if (strncmp(buf, "CK ", 3) == 0)
continue; /* ignore */
err = got_error_msg(GOT_ERR_BAD_PACKET,
"unexpected message from server");
goto done;
} else {
err = got_error_msg(GOT_ERR_BAD_PACKET,
"unknown side-band received from server");
goto done;
}
} else {
/* No sideband channel. Every byte is packfile data. */
err = readn(&r, fd, buf, sizeof buf);
if (err)
goto done;
if (r <= 0)
break;
}
/*
* An expected SHA1 checksum sits at the end of the pack file.
* Since we don't know the file size ahead of time we have to
* keep SHA1_DIGEST_LENGTH bytes buffered and avoid mixing
* those bytes into our SHA1 checksum computation until we
* know for sure that additional pack file data bytes follow.
*
* We can assume r > 0 since otherwise the loop would exit.
*/
if (r < SHA1_DIGEST_LENGTH) {
if (sha1_buf_len < SHA1_DIGEST_LENGTH) {
/*
* If there's enough buffered + read data to
* fill up the buffer then shift a sufficient
* amount of bytes out at the front to make
* room, mixing those bytes into the checksum.
*/
while (sha1_buf_len > 0 &&
sha1_buf_len + r > SHA1_DIGEST_LENGTH) {
SHA1Update(&sha1_ctx, sha1_buf, 1);
memmove(sha1_buf, sha1_buf + 1, 1);
sha1_buf_len--;
}
/* Buffer potential checksum bytes. */
memcpy(sha1_buf + sha1_buf_len, buf, r);
sha1_buf_len += r;
} else {
/*
* Mix in previously buffered bytes which
* are not part of the checksum after all.
*/
SHA1Update(&sha1_ctx, sha1_buf, r);
/* Update potential checksum buffer. */
memmove(sha1_buf, sha1_buf + r,
sha1_buf_len - r);
memcpy(sha1_buf + sha1_buf_len - r, buf, r);
}
} else {
/* Mix in any previously buffered bytes. */
SHA1Update(&sha1_ctx, sha1_buf, sha1_buf_len);
/* Mix in bytes read minus potential checksum bytes. */
SHA1Update(&sha1_ctx, buf, r - SHA1_DIGEST_LENGTH);
/* Buffer potential checksum bytes. */
memcpy(sha1_buf, buf + r - SHA1_DIGEST_LENGTH,
SHA1_DIGEST_LENGTH);
sha1_buf_len = SHA1_DIGEST_LENGTH;
}
/* Write packfile data to temporary pack file. */
w = write(packfd, buf, r);
if (w == -1) {
err = got_error_from_errno("write");
goto done;
}
if (w != r) {
err = got_error(GOT_ERR_IO);
goto done;
}
packsz += w;
/* Don't send too many progress privsep messages. */
if (packsz > last_reported_packsz + 1024) {
err = send_fetch_download_progress(ibuf, packsz);
if (err)
goto done;
last_reported_packsz = packsz;
}
}
err = send_fetch_download_progress(ibuf, packsz);
if (err)
goto done;
SHA1Final(pack_sha1, &sha1_ctx);
if (sha1_buf_len != SHA1_DIGEST_LENGTH ||
memcmp(pack_sha1, sha1_buf, sha1_buf_len) != 0) {
err = got_error_msg(GOT_ERR_BAD_PACKFILE,
"pack file checksum mismatch");
}
done:
TAILQ_FOREACH(pe, &symrefs, entry) {
free((void *)pe->path);
free(pe->data);
}
got_pathlist_free(&symrefs);
free(have);
free(want);
free(id_str);
free(refname);
free(server_capabilities);
return err;
}
int
main(int argc, char **argv)
{
const struct got_error *err = NULL;
int fetchfd, packfd = -1, i;
uint8_t pack_sha1[SHA1_DIGEST_LENGTH];
struct imsgbuf ibuf;
struct imsg imsg;
struct got_pathlist_head have_refs;
struct got_pathlist_head wanted_branches;
struct got_pathlist_head wanted_refs;
struct got_pathlist_entry *pe;
struct got_imsg_fetch_request fetch_req;
struct got_imsg_fetch_have_ref href;
struct got_imsg_fetch_wanted_branch wbranch;
struct got_imsg_fetch_wanted_ref wref;
size_t datalen;
#if 0
static int attached;
while (!attached)
sleep (1);
#endif
TAILQ_INIT(&have_refs);
TAILQ_INIT(&wanted_branches);
TAILQ_INIT(&wanted_refs);
imsg_init(&ibuf, GOT_IMSG_FD_CHILD);
#ifndef PROFILE
/* revoke access to most system calls */
if (pledge("stdio recvfd", NULL) == -1) {
err = got_error_from_errno("pledge");
got_privsep_send_error(&ibuf, err);
return 1;
}
#endif
if ((err = got_privsep_recv_imsg(&imsg, &ibuf, 0)) != 0) {
if (err->code == GOT_ERR_PRIVSEP_PIPE)
err = NULL;
goto done;
}
if (imsg.hdr.type == GOT_IMSG_STOP)
goto done;
if (imsg.hdr.type != GOT_IMSG_FETCH_REQUEST) {
err = got_error(GOT_ERR_PRIVSEP_MSG);
goto done;
}
datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
if (datalen < sizeof(fetch_req)) {
err = got_error(GOT_ERR_PRIVSEP_LEN);
goto done;
}
memcpy(&fetch_req, imsg.data, sizeof(fetch_req));
fetchfd = imsg.fd;
imsg_free(&imsg);
if (fetch_req.verbosity > 0)
chattygot += fetch_req.verbosity;
for (i = 0; i < fetch_req.n_have_refs; i++) {
struct got_object_id *id;
char *refname;
if ((err = got_privsep_recv_imsg(&imsg, &ibuf, 0)) != 0) {
if (err->code == GOT_ERR_PRIVSEP_PIPE)
err = NULL;
goto done;
}
if (imsg.hdr.type == GOT_IMSG_STOP)
goto done;
if (imsg.hdr.type != GOT_IMSG_FETCH_HAVE_REF) {
err = got_error(GOT_ERR_PRIVSEP_MSG);
goto done;
}
datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
if (datalen < sizeof(href)) {
err = got_error(GOT_ERR_PRIVSEP_LEN);
goto done;
}
memcpy(&href, imsg.data, sizeof(href));
if (datalen - sizeof(href) < href.name_len) {
err = got_error(GOT_ERR_PRIVSEP_LEN);
goto done;
}
refname = malloc(href.name_len + 1);
if (refname == NULL) {
err = got_error_from_errno("malloc");
goto done;
}
memcpy(refname, imsg.data + sizeof(href), href.name_len);
refname[href.name_len] = '\0';
id = malloc(sizeof(*id));
if (id == NULL) {
free(refname);
err = got_error_from_errno("malloc");
goto done;
}
memcpy(id->sha1, href.id, SHA1_DIGEST_LENGTH);
err = got_pathlist_append(&have_refs, refname, id);
if (err) {
free(refname);
free(id);
goto done;
}
imsg_free(&imsg);
}
for (i = 0; i < fetch_req.n_wanted_branches; i++) {
char *refname;
if ((err = got_privsep_recv_imsg(&imsg, &ibuf, 0)) != 0) {
if (err->code == GOT_ERR_PRIVSEP_PIPE)
err = NULL;
goto done;
}
if (imsg.hdr.type == GOT_IMSG_STOP)
goto done;
if (imsg.hdr.type != GOT_IMSG_FETCH_WANTED_BRANCH) {
err = got_error(GOT_ERR_PRIVSEP_MSG);
goto done;
}
datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
if (datalen < sizeof(wbranch)) {
err = got_error(GOT_ERR_PRIVSEP_LEN);
goto done;
}
memcpy(&wbranch, imsg.data, sizeof(wbranch));
if (datalen - sizeof(wbranch) < wbranch.name_len) {
err = got_error(GOT_ERR_PRIVSEP_LEN);
goto done;
}
refname = malloc(wbranch.name_len + 1);
if (refname == NULL) {
err = got_error_from_errno("malloc");
goto done;
}
memcpy(refname, imsg.data + sizeof(wbranch), wbranch.name_len);
refname[wbranch.name_len] = '\0';
err = got_pathlist_append(&wanted_branches, refname, NULL);
if (err) {
free(refname);
goto done;
}
imsg_free(&imsg);
}
for (i = 0; i < fetch_req.n_wanted_refs; i++) {
char *refname;
if ((err = got_privsep_recv_imsg(&imsg, &ibuf, 0)) != 0) {
if (err->code == GOT_ERR_PRIVSEP_PIPE)
err = NULL;
goto done;
}
if (imsg.hdr.type == GOT_IMSG_STOP)
goto done;
if (imsg.hdr.type != GOT_IMSG_FETCH_WANTED_REF) {
err = got_error(GOT_ERR_PRIVSEP_MSG);
goto done;
}
datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
if (datalen < sizeof(wref)) {
err = got_error(GOT_ERR_PRIVSEP_LEN);
goto done;
}
memcpy(&wref, imsg.data, sizeof(wref));
if (datalen - sizeof(wref) < wref.name_len) {
err = got_error(GOT_ERR_PRIVSEP_LEN);
goto done;
}
refname = malloc(wref.name_len + 1);
if (refname == NULL) {
err = got_error_from_errno("malloc");
goto done;
}
memcpy(refname, imsg.data + sizeof(wref), wref.name_len);
refname[wref.name_len] = '\0';
err = got_pathlist_append(&wanted_refs, refname, NULL);
if (err) {
free(refname);
goto done;
}
imsg_free(&imsg);
}
if ((err = got_privsep_recv_imsg(&imsg, &ibuf, 0)) != 0) {
if (err->code == GOT_ERR_PRIVSEP_PIPE)
err = NULL;
goto done;
}
if (imsg.hdr.type == GOT_IMSG_STOP)
goto done;
if (imsg.hdr.type != GOT_IMSG_FETCH_OUTFD) {
err = got_error(GOT_ERR_PRIVSEP_MSG);
goto done;
}
if (imsg.hdr.len - IMSG_HEADER_SIZE != 0) {
err = got_error(GOT_ERR_PRIVSEP_LEN);
goto done;
}
packfd = imsg.fd;
err = fetch_pack(fetchfd, packfd, pack_sha1, &have_refs,
fetch_req.fetch_all_branches, &wanted_branches,
&wanted_refs, fetch_req.list_refs_only, &ibuf);
done:
TAILQ_FOREACH(pe, &have_refs, entry) {
free((char *)pe->path);
free(pe->data);
}
got_pathlist_free(&have_refs);
TAILQ_FOREACH(pe, &wanted_branches, entry)
free((char *)pe->path);
got_pathlist_free(&wanted_branches);
if (fetchfd != -1 && close(fetchfd) == -1 && err == NULL)
err = got_error_from_errno("close");
if (packfd != -1 && close(packfd) == -1 && err == NULL)
err = got_error_from_errno("close");
if (err != NULL)
got_privsep_send_error(&ibuf, err);
else
err = send_fetch_done(&ibuf, pack_sha1);
if (err != NULL) {
fprintf(stderr, "%s: %s\n", getprogname(), err->msg);
got_privsep_send_error(&ibuf, err);
}
exit(0);
}
|
ThomasAdam/gameoftrees
|
lib/delta_cache.c
|
/*
* Copyright (c) 2019, 2020 <NAME> <<EMAIL>>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdlib.h>
#include <string.h>
#include <sha1.h>
#include <stdio.h>
#include <zlib.h>
#include <limits.h>
#include <time.h>
#include "got_compat.h"
#include "got_object.h"
#include "got_error.h"
#include "got_lib_delta.h"
#include "got_lib_inflate.h"
#include "got_lib_object.h"
#include "got_lib_delta_cache.h"
#ifndef nitems
#define nitems(_a) (sizeof(_a) / sizeof((_a)[0]))
#endif
struct got_delta_cache_element {
TAILQ_ENTRY(got_delta_cache_element) entry;
off_t delta_data_offset;
uint8_t *delta_data;
size_t delta_len;
};
TAILQ_HEAD(got_delta_cache_head, got_delta_cache_element);
struct got_delta_cache {
struct got_delta_cache_head entries;
int nelem;
int maxelem;
size_t maxelemsize;
int cache_search;
int cache_hit;
int cache_miss;
int cache_evict;
int cache_toolarge;
};
struct got_delta_cache *
got_delta_cache_alloc(int maxelem, size_t maxelemsize)
{
struct got_delta_cache *cache;
cache = calloc(1, sizeof(*cache));
if (cache == NULL)
return NULL;
TAILQ_INIT(&cache->entries);
cache->maxelem = maxelem;
cache->maxelemsize = maxelemsize;
return cache;
}
void
got_delta_cache_free(struct got_delta_cache *cache)
{
struct got_delta_cache_element *entry;
#ifdef GOT_OBJ_CACHE_DEBUG
fprintf(stderr, "%s: delta cache: %d elements, %d searches, %d hits, "
"%d missed, %d evicted, %d too large\n", getprogname(), cache->nelem,
cache->cache_search, cache->cache_hit, cache->cache_miss,
cache->cache_evict, cache->cache_toolarge);
#endif
while (!TAILQ_EMPTY(&cache->entries)) {
entry = TAILQ_FIRST(&cache->entries);
TAILQ_REMOVE(&cache->entries, entry, entry);
free(entry->delta_data);
free(entry);
}
free(cache);
}
#ifndef GOT_NO_OBJ_CACHE
static void
remove_least_used_element(struct got_delta_cache *cache)
{
struct got_delta_cache_element *entry;
if (cache->nelem == 0)
return;
entry = TAILQ_LAST(&cache->entries, got_delta_cache_head);
TAILQ_REMOVE(&cache->entries, entry, entry);
free(entry->delta_data);
free(entry);
cache->nelem--;
cache->cache_evict++;
}
#endif
const struct got_error *
got_delta_cache_add(struct got_delta_cache *cache,
off_t delta_data_offset, uint8_t *delta_data, size_t delta_len)
{
#ifdef GOT_NO_OBJ_CACHE
return got_error(GOT_ERR_NO_SPACE);
#else
struct got_delta_cache_element *entry;
if (delta_len > cache->maxelemsize) {
cache->cache_toolarge++;
return got_error(GOT_ERR_NO_SPACE);
}
if (cache->nelem >= cache->maxelem)
remove_least_used_element(cache);
entry = calloc(1, sizeof(*entry));
if (entry == NULL)
return got_error_from_errno("calloc");
entry->delta_data_offset = delta_data_offset;
entry->delta_data = delta_data;
entry->delta_len = delta_len;
TAILQ_INSERT_HEAD(&cache->entries, entry, entry);
cache->nelem++;
return NULL;
#endif
}
void
got_delta_cache_get(uint8_t **delta_data, size_t *delta_len,
struct got_delta_cache *cache, off_t delta_data_offset)
{
struct got_delta_cache_element *entry;
cache->cache_search++;
*delta_data = NULL;
*delta_len = 0;
TAILQ_FOREACH(entry, &cache->entries, entry) {
if (entry->delta_data_offset != delta_data_offset)
continue;
cache->cache_hit++;
if (entry != TAILQ_FIRST(&cache->entries)) {
TAILQ_REMOVE(&cache->entries, entry, entry);
TAILQ_INSERT_HEAD(&cache->entries, entry, entry);
}
*delta_data = entry->delta_data;
*delta_len = entry->delta_len;
return;
}
cache->cache_miss++;
}
|
ThomasAdam/gameoftrees
|
include/got_compat.h
|
<filename>include/got_compat.h
#ifndef _GOT_COMPAT_H
#define _GOT_COMPAT_H
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/uio.h>
#include <fnmatch.h>
#include <limits.h>
#include <stdio.h>
#include <stdint.h>
/*
#include <termios.h>
#include <wchar.h>
*/
/* For flock. */
#ifndef O_EXLOCK
#define O_EXLOCK 0
#endif
#ifndef HAVE_FLOCK
#define LOCK_SH 0
#define LOCK_EX 0
#define LOCK_NB 0
#define flock(fd, op) (0)
#else
#include <sys/file.h>
#endif
#ifndef __dead
#define __dead __attribute__ ((__noreturn__))
#endif
#ifndef __OpenBSD__
#define pledge(s, p) (0)
#define unveil(s, p) (0)
#endif
#ifndef INFTIM
#define INFTIM -1
#endif
#ifndef HAVE_BSD_UUID
#include <uuid/uuid.h>
#define uuid_s_ok 0
#define uuid_s_bad_version 1
#define uuid_s_invalid_string_uuid 2
#define uuid_s_no_memory 3
/* Length of a node address (an IEEE 802 address). */
#define _UUID_NODE_LEN 6
struct uuid {
uint32_t time_low;
uint16_t time_mid;
uint16_t time_hi_and_version;
uint8_t clock_seq_hi_and_reserved;
uint8_t clock_seq_low;
uint8_t node[_UUID_NODE_LEN];
};
int32_t uuid_equal(struct uuid *, struct uuid *, uint32_t *);
int32_t uuid_is_nil(struct uuid *, uint32_t *);
void uuid_create(uuid_t *, uint32_t *);
void uuid_create_nil(struct uuid *, uint32_t *);
void uuid_from_string(const char *, uuid_t *, uint32_t *);
void uuid_to_string(uuid_t *, char **, uint32_t *);
#endif
#ifdef HAVE_STDINT_H
#include <stdint.h>
#else
#include <inttypes.h>
#endif
#ifdef HAVE_QUEUE_H
#include <sys/queue.h>
#else
#include "compat/queue.h"
#endif
#ifdef HAVE_TREE_H
#include <sys/tree.h>
#else
#include "compat/tree.h"
#endif
#ifdef HAVE_UTIL_H
#include <util.h>
#endif
#ifdef HAVE_LIBUTIL_H
#include <libutil.h>
#endif
#ifdef HAVE_IMSG
#else
#include "compat/imsg.h"
#endif
#ifndef HAVE_ASPRINTF
/* asprintf.c */
int asprintf(char **, const char *, ...);
int vasprintf(char **, const char *, va_list);
#endif
#ifndef HAVE_EXPLICIT_BZERO
/* explicit_bzero.c */
void explicit_bzero(void *, size_t);
#endif
#ifndef HAVE_GETDTABLECOUNT
/* getdtablecount.c */
int getdtablecount(void);
#endif
#ifndef HAVE_CLOSEFROM
/* closefrom.c */
//void closefrom(int);
#define closefrom(fd) (closefrom(fd), 0)
#endif
#ifndef HAVE_STRSEP
/* strsep.c */
char *strsep(char **, const char *);
#endif
#ifndef HAVE_STRTONUM
/* strtonum.c */
long long strtonum(const char *, long long, long long, const char **);
#endif
#ifndef HAVE_STRLCPY
/* strlcpy.c */
size_t strlcpy(char *, const char *, size_t);
#endif
#ifndef HAVE_STRLCAT
/* strlcat.c */
size_t strlcat(char *, const char *, size_t);
#endif
#ifndef HAVE_STRNLEN
/* strnlen.c */
size_t strnlen(const char *, size_t);
#endif
#ifndef HAVE_STRNDUP
/* strndup.c */
char *strndup(const char *, size_t);
#endif
#ifndef HAVE_GETPROGNAME
/* getprogname.c */
const char *getprogname(void);
#endif
#ifndef HAVE_GETLINE
/* getline.c */
ssize_t getline(char **, size_t *, FILE *);
#endif
#ifndef HAVE_FREEZERO
/* freezero.c */
void freezero(void *, size_t);
#endif
#ifndef HAVE_GETDTABLECOUNT
/* getdtablecount.c */
int getdtablecount(void);
#endif
#ifndef HAVE_REALLOCARRAY
/* reallocarray.c */
void *reallocarray(void *, size_t, size_t);
#endif
#ifndef HAVE_RECALLOCARRAY
/* recallocarray.c */
void *recallocarray(void *, size_t, size_t, size_t);
#endif
#ifndef HAVE_FMT_SCALED
/* fmt_scaled.c */
int fmt_scaled(long long, char *);
int scan_scaled(char *, long long *);
#define FMT_SCALED_STRSIZE 7 /* minus sign, 4 digits, suffix, null byte */
#endif
#ifndef HAVE_LIBBSD
/* getopt.c */
extern int BSDopterr;
extern int BSDoptind;
extern int BSDoptopt;
extern int BSDoptreset;
extern char *BSDoptarg;
int BSDgetopt(int, char *const *, const char *);
#define getopt(ac, av, o) BSDgetopt(ac, av, o)
#define opterr BSDopterr
#define optind BSDoptind
#define optopt BSDoptopt
#define optreset BSDoptreset
#define optarg BSDoptarg
#endif
#endif
#ifndef HAVE_BSD_MERGESORT
/* mergesort.c */
int mergesort(void *, size_t, size_t, int (*)(const void *, const void *));
#endif
|
ThomasAdam/gameoftrees
|
lib/repository.c
|
/*
* Copyright (c) 2018, 2019, 2020 <NAME> <<EMAIL>>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <ctype.h>
#include <endian.h>
#include <fcntl.h>
#include <fnmatch.h>
#include <limits.h>
#include <dirent.h>
#include <stdlib.h>
#include <stdio.h>
#include <sha1.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <zlib.h>
#include <errno.h>
#include <libgen.h>
#include <stdint.h>
#include <uuid.h>
#include "got_compat.h"
#include "got_error.h"
#include "got_reference.h"
#include "got_repository.h"
#include "got_path.h"
#include "got_cancel.h"
#include "got_worktree.h"
#include "got_object.h"
#include "got_lib_delta.h"
#include "got_lib_inflate.h"
#include "got_lib_object.h"
#include "got_lib_object_parse.h"
#include "got_lib_object_create.h"
#include "got_lib_pack.h"
#include "got_lib_privsep.h"
#include "got_lib_worktree.h"
#include "got_lib_sha1.h"
#include "got_lib_object_cache.h"
#include "got_lib_repository.h"
#include "got_lib_gotconfig.h"
#ifndef nitems
#define nitems(_a) (sizeof(_a) / sizeof((_a)[0]))
#endif
const char *
got_repo_get_path(struct got_repository *repo)
{
return repo->path;
}
const char *
got_repo_get_path_git_dir(struct got_repository *repo)
{
return repo->path_git_dir;
}
int
got_repo_get_fd(struct got_repository *repo)
{
return repo->gitdir_fd;
}
const char *
got_repo_get_gitconfig_author_name(struct got_repository *repo)
{
return repo->gitconfig_author_name;
}
const char *
got_repo_get_gitconfig_author_email(struct got_repository *repo)
{
return repo->gitconfig_author_email;
}
const char *
got_repo_get_global_gitconfig_author_name(struct got_repository *repo)
{
return repo->global_gitconfig_author_name;
}
const char *
got_repo_get_global_gitconfig_author_email(struct got_repository *repo)
{
return repo->global_gitconfig_author_email;
}
const char *
got_repo_get_gitconfig_owner(struct got_repository *repo)
{
return repo->gitconfig_owner;
}
int
got_repo_is_bare(struct got_repository *repo)
{
return (strcmp(repo->path, repo->path_git_dir) == 0);
}
static char *
get_path_git_child(struct got_repository *repo, const char *basename)
{
char *path_child;
if (asprintf(&path_child, "%s/%s", repo->path_git_dir,
basename) == -1)
return NULL;
return path_child;
}
char *
got_repo_get_path_objects(struct got_repository *repo)
{
return get_path_git_child(repo, GOT_OBJECTS_DIR);
}
char *
got_repo_get_path_objects_pack(struct got_repository *repo)
{
return get_path_git_child(repo, GOT_OBJECTS_PACK_DIR);
}
char *
got_repo_get_path_refs(struct got_repository *repo)
{
return get_path_git_child(repo, GOT_REFS_DIR);
}
char *
got_repo_get_path_packed_refs(struct got_repository *repo)
{
return get_path_git_child(repo, GOT_PACKED_REFS_FILE);
}
static char *
get_path_head(struct got_repository *repo)
{
return get_path_git_child(repo, GOT_HEAD_FILE);
}
char *
got_repo_get_path_gitconfig(struct got_repository *repo)
{
return get_path_git_child(repo, GOT_GITCONFIG);
}
char *
got_repo_get_path_gotconfig(struct got_repository *repo)
{
return get_path_git_child(repo, GOT_GOTCONFIG_FILENAME);
}
const struct got_gotconfig *
got_repo_get_gotconfig(struct got_repository *repo)
{
return repo->gotconfig;
}
void
got_repo_get_gitconfig_remotes(int *nremotes,
const struct got_remote_repo **remotes, struct got_repository *repo)
{
*nremotes = repo->ngitconfig_remotes;
*remotes = repo->gitconfig_remotes;
}
static int
is_git_repo(struct got_repository *repo)
{
const char *path_git = got_repo_get_path_git_dir(repo);
char *path_objects = got_repo_get_path_objects(repo);
char *path_refs = got_repo_get_path_refs(repo);
char *path_head = get_path_head(repo);
int ret = 0;
struct stat sb;
struct got_reference *head_ref;
if (lstat(path_git, &sb) == -1)
goto done;
if (!S_ISDIR(sb.st_mode))
goto done;
if (lstat(path_objects, &sb) == -1)
goto done;
if (!S_ISDIR(sb.st_mode))
goto done;
if (lstat(path_refs, &sb) == -1)
goto done;
if (!S_ISDIR(sb.st_mode))
goto done;
if (lstat(path_head, &sb) == -1)
goto done;
if (!S_ISREG(sb.st_mode))
goto done;
/* Check if the HEAD reference can be opened. */
if (got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0) != NULL)
goto done;
got_ref_close(head_ref);
ret = 1;
done:
free(path_objects);
free(path_refs);
free(path_head);
return ret;
}
const struct got_error *
got_repo_cache_object(struct got_repository *repo, struct got_object_id *id,
struct got_object *obj)
{
#ifndef GOT_NO_OBJ_CACHE
const struct got_error *err = NULL;
err = got_object_cache_add(&repo->objcache, id, obj);
if (err) {
if (err->code == GOT_ERR_OBJ_EXISTS ||
err->code == GOT_ERR_OBJ_TOO_LARGE)
err = NULL;
return err;
}
obj->refcnt++;
#endif
return NULL;
}
struct got_object *
got_repo_get_cached_object(struct got_repository *repo,
struct got_object_id *id)
{
return (struct got_object *)got_object_cache_get(&repo->objcache, id);
}
const struct got_error *
got_repo_cache_tree(struct got_repository *repo, struct got_object_id *id,
struct got_tree_object *tree)
{
#ifndef GOT_NO_OBJ_CACHE
const struct got_error *err = NULL;
err = got_object_cache_add(&repo->treecache, id, tree);
if (err) {
if (err->code == GOT_ERR_OBJ_EXISTS ||
err->code == GOT_ERR_OBJ_TOO_LARGE)
err = NULL;
return err;
}
tree->refcnt++;
#endif
return NULL;
}
struct got_tree_object *
got_repo_get_cached_tree(struct got_repository *repo,
struct got_object_id *id)
{
return (struct got_tree_object *)got_object_cache_get(
&repo->treecache, id);
}
const struct got_error *
got_repo_cache_commit(struct got_repository *repo, struct got_object_id *id,
struct got_commit_object *commit)
{
#ifndef GOT_NO_OBJ_CACHE
const struct got_error *err = NULL;
err = got_object_cache_add(&repo->commitcache, id, commit);
if (err) {
if (err->code == GOT_ERR_OBJ_EXISTS ||
err->code == GOT_ERR_OBJ_TOO_LARGE)
err = NULL;
return err;
}
commit->refcnt++;
#endif
return NULL;
}
struct got_commit_object *
got_repo_get_cached_commit(struct got_repository *repo,
struct got_object_id *id)
{
return (struct got_commit_object *)got_object_cache_get(
&repo->commitcache, id);
}
const struct got_error *
got_repo_cache_tag(struct got_repository *repo, struct got_object_id *id,
struct got_tag_object *tag)
{
#ifndef GOT_NO_OBJ_CACHE
const struct got_error *err = NULL;
err = got_object_cache_add(&repo->tagcache, id, tag);
if (err) {
if (err->code == GOT_ERR_OBJ_EXISTS ||
err->code == GOT_ERR_OBJ_TOO_LARGE)
err = NULL;
return err;
}
tag->refcnt++;
#endif
return NULL;
}
struct got_tag_object *
got_repo_get_cached_tag(struct got_repository *repo, struct got_object_id *id)
{
return (struct got_tag_object *)got_object_cache_get(
&repo->tagcache, id);
}
const struct got_error *
open_repo(struct got_repository *repo, const char *path)
{
const struct got_error *err = NULL;
repo->gitdir_fd = -1;
/* bare git repository? */
repo->path_git_dir = strdup(path);
if (repo->path_git_dir == NULL)
return got_error_from_errno("strdup");
if (is_git_repo(repo)) {
repo->path = strdup(repo->path_git_dir);
if (repo->path == NULL) {
err = got_error_from_errno("strdup");
goto done;
}
repo->gitdir_fd = open(repo->path_git_dir, O_DIRECTORY);
if (repo->gitdir_fd == -1) {
err = got_error_from_errno2("open",
repo->path_git_dir);
goto done;
}
return NULL;
}
/* git repository with working tree? */
free(repo->path_git_dir);
repo->path_git_dir = NULL;
if (asprintf(&repo->path_git_dir, "%s/%s", path, GOT_GIT_DIR) == -1) {
err = got_error_from_errno("asprintf");
goto done;
}
if (is_git_repo(repo)) {
repo->path = strdup(path);
if (repo->path == NULL) {
err = got_error_from_errno("strdup");
goto done;
}
repo->gitdir_fd = open(repo->path_git_dir, O_DIRECTORY);
if (repo->gitdir_fd == -1) {
err = got_error_from_errno2("open",
repo->path_git_dir);
goto done;
}
return NULL;
}
err = got_error(GOT_ERR_NOT_GIT_REPO);
done:
if (err) {
free(repo->path);
repo->path = NULL;
free(repo->path_git_dir);
repo->path_git_dir = NULL;
if (repo->gitdir_fd != -1)
close(repo->gitdir_fd);
repo->gitdir_fd = -1;
}
return err;
}
static const struct got_error *
parse_gitconfig_file(int *gitconfig_repository_format_version,
char **gitconfig_author_name, char **gitconfig_author_email,
struct got_remote_repo **remotes, int *nremotes,
char **gitconfig_owner, char ***extensions, int *nextensions,
const char *gitconfig_path)
{
const struct got_error *err = NULL, *child_err = NULL;
int fd = -1;
int imsg_fds[2] = { -1, -1 };
pid_t pid;
struct imsgbuf *ibuf;
*gitconfig_repository_format_version = 0;
if (extensions)
*extensions = NULL;
if (nextensions)
*nextensions = 0;
*gitconfig_author_name = NULL;
*gitconfig_author_email = NULL;
if (remotes)
*remotes = NULL;
if (nremotes)
*nremotes = 0;
if (gitconfig_owner)
*gitconfig_owner = NULL;
fd = open(gitconfig_path, O_RDONLY);
if (fd == -1) {
if (errno == ENOENT)
return NULL;
return got_error_from_errno2("open", gitconfig_path);
}
ibuf = calloc(1, sizeof(*ibuf));
if (ibuf == NULL) {
err = got_error_from_errno("calloc");
goto done;
}
if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, imsg_fds) == -1) {
err = got_error_from_errno("socketpair");
goto done;
}
pid = fork();
if (pid == -1) {
err = got_error_from_errno("fork");
goto done;
} else if (pid == 0) {
got_privsep_exec_child(imsg_fds, GOT_PATH_PROG_READ_GITCONFIG,
gitconfig_path);
/* not reached */
}
if (close(imsg_fds[1]) == -1) {
err = got_error_from_errno("close");
goto done;
}
imsg_fds[1] = -1;
imsg_init(ibuf, imsg_fds[0]);
err = got_privsep_send_gitconfig_parse_req(ibuf, fd);
if (err)
goto done;
fd = -1;
err = got_privsep_send_gitconfig_repository_format_version_req(ibuf);
if (err)
goto done;
err = got_privsep_recv_gitconfig_int(
gitconfig_repository_format_version, ibuf);
if (err)
goto done;
if (extensions && nextensions) {
err = got_privsep_send_gitconfig_repository_extensions_req(
ibuf);
if (err)
goto done;
err = got_privsep_recv_gitconfig_int(nextensions, ibuf);
if (err)
goto done;
if (*nextensions > 0) {
int i;
*extensions = calloc(*nextensions, sizeof(char *));
if (*extensions == NULL) {
err = got_error_from_errno("calloc");
goto done;
}
for (i = 0; i < *nextensions; i++) {
char *ext;
err = got_privsep_recv_gitconfig_str(&ext,
ibuf);
if (err)
goto done;
(*extensions)[i] = ext;
}
}
}
err = got_privsep_send_gitconfig_author_name_req(ibuf);
if (err)
goto done;
err = got_privsep_recv_gitconfig_str(gitconfig_author_name, ibuf);
if (err)
goto done;
err = got_privsep_send_gitconfig_author_email_req(ibuf);
if (err)
goto done;
err = got_privsep_recv_gitconfig_str(gitconfig_author_email, ibuf);
if (err)
goto done;
if (remotes && nremotes) {
err = got_privsep_send_gitconfig_remotes_req(ibuf);
if (err)
goto done;
err = got_privsep_recv_gitconfig_remotes(remotes,
nremotes, ibuf);
if (err)
goto done;
}
if (gitconfig_owner) {
err = got_privsep_send_gitconfig_owner_req(ibuf);
if (err)
goto done;
err = got_privsep_recv_gitconfig_str(gitconfig_owner, ibuf);
if (err)
goto done;
}
imsg_clear(ibuf);
err = got_privsep_send_stop(imsg_fds[0]);
child_err = got_privsep_wait_for_child(pid);
if (child_err && err == NULL)
err = child_err;
done:
if (imsg_fds[0] != -1 && close(imsg_fds[0]) == -1 && err == NULL)
err = got_error_from_errno("close");
if (imsg_fds[1] != -1 && close(imsg_fds[1]) == -1 && err == NULL)
err = got_error_from_errno("close");
if (fd != -1 && close(fd) == -1 && err == NULL)
err = got_error_from_errno2("close", gitconfig_path);
free(ibuf);
return err;
}
static const struct got_error *
read_gitconfig(struct got_repository *repo, const char *global_gitconfig_path)
{
const struct got_error *err = NULL;
char *repo_gitconfig_path = NULL;
if (global_gitconfig_path) {
/* Read settings from ~/.gitconfig. */
int dummy_repo_version;
err = parse_gitconfig_file(&dummy_repo_version,
&repo->global_gitconfig_author_name,
&repo->global_gitconfig_author_email,
NULL, NULL, NULL, NULL, NULL, global_gitconfig_path);
if (err)
return err;
}
/* Read repository's .git/config file. */
repo_gitconfig_path = got_repo_get_path_gitconfig(repo);
if (repo_gitconfig_path == NULL)
return got_error_from_errno("got_repo_get_path_gitconfig");
err = parse_gitconfig_file(&repo->gitconfig_repository_format_version,
&repo->gitconfig_author_name, &repo->gitconfig_author_email,
&repo->gitconfig_remotes, &repo->ngitconfig_remotes,
&repo->gitconfig_owner, &repo->extensions, &repo->nextensions,
repo_gitconfig_path);
if (err)
goto done;
done:
free(repo_gitconfig_path);
return err;
}
static const struct got_error *
read_gotconfig(struct got_repository *repo)
{
const struct got_error *err = NULL;
char *gotconfig_path;
gotconfig_path = got_repo_get_path_gotconfig(repo);
if (gotconfig_path == NULL)
return got_error_from_errno("got_repo_get_path_gotconfig");
err = got_gotconfig_read(&repo->gotconfig, gotconfig_path);
free(gotconfig_path);
return err;
}
/* Supported repository format extensions. */
static const char *repo_extensions[] = {
"noop", /* Got supports repository format version 1. */
"preciousObjects", /* Got has no garbage collection yet. */
"worktreeConfig", /* Got does not care about Git work trees. */
};
const struct got_error *
got_repo_open(struct got_repository **repop, const char *path,
const char *global_gitconfig_path)
{
struct got_repository *repo = NULL;
const struct got_error *err = NULL;
char *repo_path = NULL;
size_t i;
*repop = NULL;
repo = calloc(1, sizeof(*repo));
if (repo == NULL) {
err = got_error_from_errno("calloc");
goto done;
}
for (i = 0; i < nitems(repo->privsep_children); i++) {
memset(&repo->privsep_children[i], 0,
sizeof(repo->privsep_children[0]));
repo->privsep_children[i].imsg_fd = -1;
}
err = got_object_cache_init(&repo->objcache,
GOT_OBJECT_CACHE_TYPE_OBJ);
if (err)
goto done;
err = got_object_cache_init(&repo->treecache,
GOT_OBJECT_CACHE_TYPE_TREE);
if (err)
goto done;
err = got_object_cache_init(&repo->commitcache,
GOT_OBJECT_CACHE_TYPE_COMMIT);
if (err)
goto done;
err = got_object_cache_init(&repo->tagcache,
GOT_OBJECT_CACHE_TYPE_TAG);
if (err)
goto done;
repo_path = realpath(path, NULL);
if (repo_path == NULL) {
err = got_error_from_errno2("realpath", path);
goto done;
}
for (;;) {
char *parent_path;
err = open_repo(repo, repo_path);
if (err == NULL)
break;
if (err->code != GOT_ERR_NOT_GIT_REPO)
goto done;
if (repo_path[0] == '/' && repo_path[1] == '\0') {
err = got_error(GOT_ERR_NOT_GIT_REPO);
goto done;
}
err = got_path_dirname(&parent_path, repo_path);
if (err)
goto done;
free(repo_path);
repo_path = parent_path;
}
err = read_gotconfig(repo);
if (err)
goto done;
err = read_gitconfig(repo, global_gitconfig_path);
if (err)
goto done;
if (repo->gitconfig_repository_format_version != 0)
err = got_error_path(path, GOT_ERR_GIT_REPO_FORMAT);
for (i = 0; i < repo->nextensions; i++) {
char *ext = repo->extensions[i];
int j, supported = 0;
for (j = 0; j < nitems(repo_extensions); j++) {
if (strcmp(ext, repo_extensions[j]) == 0) {
supported = 1;
break;
}
}
if (!supported) {
err = got_error_path(ext, GOT_ERR_GIT_REPO_EXT);
goto done;
}
}
done:
if (err)
got_repo_close(repo);
else
*repop = repo;
free(repo_path);
return err;
}
const struct got_error *
got_repo_close(struct got_repository *repo)
{
const struct got_error *err = NULL, *child_err;
size_t i;
for (i = 0; i < nitems(repo->packidx_cache); i++) {
if (repo->packidx_cache[i] == NULL)
break;
got_packidx_close(repo->packidx_cache[i]);
}
for (i = 0; i < nitems(repo->packs); i++) {
if (repo->packs[i].path_packfile == NULL)
break;
got_pack_close(&repo->packs[i]);
}
free(repo->path);
free(repo->path_git_dir);
got_object_cache_close(&repo->objcache);
got_object_cache_close(&repo->treecache);
got_object_cache_close(&repo->commitcache);
got_object_cache_close(&repo->tagcache);
for (i = 0; i < nitems(repo->privsep_children); i++) {
if (repo->privsep_children[i].imsg_fd == -1)
continue;
imsg_clear(repo->privsep_children[i].ibuf);
free(repo->privsep_children[i].ibuf);
err = got_privsep_send_stop(repo->privsep_children[i].imsg_fd);
child_err = got_privsep_wait_for_child(
repo->privsep_children[i].pid);
if (child_err && err == NULL)
err = child_err;
if (close(repo->privsep_children[i].imsg_fd) != 0 &&
err == NULL)
err = got_error_from_errno("close");
}
if (repo->gotconfig)
got_gotconfig_free(repo->gotconfig);
free(repo->gitconfig_author_name);
free(repo->gitconfig_author_email);
for (i = 0; i < repo->ngitconfig_remotes; i++)
got_repo_free_remote_repo_data(&repo->gitconfig_remotes[i]);
free(repo->gitconfig_remotes);
for (i = 0; i < repo->nextensions; i++)
free(repo->extensions[i]);
free(repo->extensions);
free(repo);
return err;
}
void
got_repo_free_remote_repo_data(struct got_remote_repo *repo)
{
int i;
free(repo->name);
repo->name = NULL;
free(repo->url);
repo->url = NULL;
for (i = 0; i < repo->nbranches; i++)
free(repo->branches[i]);
free(repo->branches);
repo->branches = NULL;
repo->nbranches = 0;
}
const struct got_error *
got_repo_map_path(char **in_repo_path, struct got_repository *repo,
const char *input_path)
{
const struct got_error *err = NULL;
const char *repo_abspath = NULL;
size_t repolen, len;
char *canonpath, *path = NULL;
*in_repo_path = NULL;
canonpath = strdup(input_path);
if (canonpath == NULL) {
err = got_error_from_errno("strdup");
goto done;
}
err = got_canonpath(input_path, canonpath, strlen(canonpath) + 1);
if (err)
goto done;
repo_abspath = got_repo_get_path(repo);
if (canonpath[0] == '\0') {
path = strdup(canonpath);
if (path == NULL) {
err = got_error_from_errno("strdup");
goto done;
}
} else {
path = realpath(canonpath, NULL);
if (path == NULL) {
if (errno != ENOENT) {
err = got_error_from_errno2("realpath",
canonpath);
goto done;
}
/*
* Path is not on disk.
* Assume it is already relative to repository root.
*/
path = strdup(canonpath);
if (path == NULL) {
err = got_error_from_errno("strdup");
goto done;
}
}
repolen = strlen(repo_abspath);
len = strlen(path);
if (strcmp(path, repo_abspath) == 0) {
free(path);
path = strdup("");
if (path == NULL) {
err = got_error_from_errno("strdup");
goto done;
}
} else if (len > repolen &&
got_path_is_child(path, repo_abspath, repolen)) {
/* Matched an on-disk path inside repository. */
if (got_repo_is_bare(repo)) {
/*
* Matched an on-disk path inside repository
* database. Treat input as repository-relative.
*/
free(path);
path = canonpath;
canonpath = NULL;
} else {
char *child;
/* Strip common prefix with repository path. */
err = got_path_skip_common_ancestor(&child,
repo_abspath, path);
if (err)
goto done;
free(path);
path = child;
}
} else {
/*
* Matched unrelated on-disk path.
* Treat input as repository-relative.
*/
free(path);
path = canonpath;
canonpath = NULL;
}
}
/* Make in-repository path absolute */
if (path[0] != '/') {
char *abspath;
if (asprintf(&abspath, "/%s", path) == -1) {
err = got_error_from_errno("asprintf");
goto done;
}
free(path);
path = abspath;
}
done:
free(canonpath);
if (err)
free(path);
else
*in_repo_path = path;
return err;
}
static const struct got_error *
cache_packidx(struct got_repository *repo, struct got_packidx *packidx,
const char *path_packidx)
{
const struct got_error *err = NULL;
size_t i;
for (i = 0; i < nitems(repo->packidx_cache); i++) {
if (repo->packidx_cache[i] == NULL)
break;
if (strcmp(repo->packidx_cache[i]->path_packidx,
path_packidx) == 0) {
return got_error(GOT_ERR_CACHE_DUP_ENTRY);
}
}
if (i == nitems(repo->packidx_cache)) {
err = got_packidx_close(repo->packidx_cache[i - 1]);
if (err)
return err;
}
/*
* Insert the new pack index at the front so it will
* be searched first in the future.
*/
memmove(&repo->packidx_cache[1], &repo->packidx_cache[0],
sizeof(repo->packidx_cache) -
sizeof(repo->packidx_cache[0]));
repo->packidx_cache[0] = packidx;
return NULL;
}
static int
is_packidx_filename(const char *name, size_t len)
{
if (len != GOT_PACKIDX_NAMELEN)
return 0;
if (strncmp(name, GOT_PACK_PREFIX, strlen(GOT_PACK_PREFIX)) != 0)
return 0;
if (strcmp(name + strlen(GOT_PACK_PREFIX) +
SHA1_DIGEST_STRING_LENGTH - 1, GOT_PACKIDX_SUFFIX) != 0)
return 0;
return 1;
}
const struct got_error *
got_repo_search_packidx(struct got_packidx **packidx, int *idx,
struct got_repository *repo, struct got_object_id *id)
{
const struct got_error *err;
DIR *packdir = NULL;
struct dirent *dent;
char *path_packidx;
size_t i;
int packdir_fd;
/* Search pack index cache. */
for (i = 0; i < nitems(repo->packidx_cache); i++) {
if (repo->packidx_cache[i] == NULL)
break;
*idx = got_packidx_get_object_idx(repo->packidx_cache[i], id);
if (*idx != -1) {
*packidx = repo->packidx_cache[i];
/*
* Move this cache entry to the front. Repeatedly
* searching a wrong pack index can be expensive.
*/
if (i > 0) {
struct got_packidx *p;
p = repo->packidx_cache[0];
repo->packidx_cache[0] = *packidx;
repo->packidx_cache[i] = p;
}
return NULL;
}
}
/* No luck. Search the filesystem. */
packdir_fd = openat(got_repo_get_fd(repo),
GOT_OBJECTS_PACK_DIR, O_DIRECTORY);
if (packdir_fd == -1) {
if (errno == ENOENT)
err = got_error_no_obj(id);
else
err = got_error_from_errno_fmt("openat: %s/%s",
got_repo_get_path_git_dir(repo),
GOT_OBJECTS_PACK_DIR);
goto done;
}
packdir = fdopendir(packdir_fd);
if (packdir == NULL) {
err = got_error_from_errno("fdopendir");
goto done;
}
while ((dent = readdir(packdir)) != NULL) {
int is_cached = 0;
if (!is_packidx_filename(dent->d_name, strlen(dent->d_name)))
continue;
if (asprintf(&path_packidx, "%s/%s", GOT_OBJECTS_PACK_DIR,
dent->d_name) == -1) {
err = got_error_from_errno("asprintf");
goto done;
}
for (i = 0; i < nitems(repo->packidx_cache); i++) {
if (repo->packidx_cache[i] == NULL)
break;
if (strcmp(repo->packidx_cache[i]->path_packidx,
path_packidx) == 0) {
is_cached = 1;
break;
}
}
if (is_cached) {
free(path_packidx);
continue; /* already searched */
}
err = got_packidx_open(packidx, got_repo_get_fd(repo),
path_packidx, 0);
if (err) {
free(path_packidx);
goto done;
}
err = cache_packidx(repo, *packidx, path_packidx);
free(path_packidx);
if (err)
goto done;
*idx = got_packidx_get_object_idx(*packidx, id);
if (*idx != -1) {
err = NULL; /* found the object */
goto done;
}
}
err = got_error_no_obj(id);
done:
if (packdir && closedir(packdir) != 0 && err == NULL)
err = got_error_from_errno("closedir");
return err;
}
static const struct got_error *
read_packfile_hdr(int fd, struct got_packidx *packidx)
{
const struct got_error *err = NULL;
uint32_t totobj = be32toh(packidx->hdr.fanout_table[0xff]);
struct got_packfile_hdr hdr;
ssize_t n;
n = read(fd, &hdr, sizeof(hdr));
if (n < 0)
return got_error_from_errno("read");
if (n != sizeof(hdr))
return got_error(GOT_ERR_BAD_PACKFILE);
if (be32toh(hdr.signature) != GOT_PACKFILE_SIGNATURE ||
be32toh(hdr.version) != GOT_PACKFILE_VERSION ||
be32toh(hdr.nobjects) != totobj)
err = got_error(GOT_ERR_BAD_PACKFILE);
return err;
}
static const struct got_error *
open_packfile(int *fd, struct got_repository *repo,
const char *relpath, struct got_packidx *packidx)
{
const struct got_error *err = NULL;
*fd = openat(got_repo_get_fd(repo), relpath, O_RDONLY | O_NOFOLLOW);
if (*fd == -1)
return got_error_from_errno_fmt("openat: %s/%s",
got_repo_get_path_git_dir(repo), relpath);
if (packidx) {
err = read_packfile_hdr(*fd, packidx);
if (err) {
close(*fd);
*fd = -1;
}
}
return err;
}
const struct got_error *
got_repo_cache_pack(struct got_pack **packp, struct got_repository *repo,
const char *path_packfile, struct got_packidx *packidx)
{
const struct got_error *err = NULL;
struct got_pack *pack = NULL;
struct stat sb;
size_t i;
if (packp)
*packp = NULL;
for (i = 0; i < nitems(repo->packs); i++) {
pack = &repo->packs[i];
if (pack->path_packfile == NULL)
break;
if (strcmp(pack->path_packfile, path_packfile) == 0)
return got_error(GOT_ERR_CACHE_DUP_ENTRY);
}
if (i == nitems(repo->packs) - 1) {
err = got_pack_close(&repo->packs[i - 1]);
if (err)
return err;
memmove(&repo->packs[1], &repo->packs[0],
sizeof(repo->packs) - sizeof(repo->packs[0]));
i = 0;
}
pack = &repo->packs[i];
pack->path_packfile = strdup(path_packfile);
if (pack->path_packfile == NULL) {
err = got_error_from_errno("strdup");
goto done;
}
err = open_packfile(&pack->fd, repo, path_packfile, packidx);
if (err)
goto done;
if (fstat(pack->fd, &sb) != 0) {
err = got_error_from_errno("fstat");
goto done;
}
pack->filesize = sb.st_size;
pack->privsep_child = NULL;
#ifndef GOT_PACK_NO_MMAP
pack->map = mmap(NULL, pack->filesize, PROT_READ, MAP_PRIVATE,
pack->fd, 0);
if (pack->map == MAP_FAILED) {
if (errno != ENOMEM) {
err = got_error_from_errno("mmap");
goto done;
}
pack->map = NULL; /* fall back to read(2) */
}
#endif
done:
if (err) {
if (pack) {
free(pack->path_packfile);
memset(pack, 0, sizeof(*pack));
}
} else if (packp)
*packp = pack;
return err;
}
struct got_pack *
got_repo_get_cached_pack(struct got_repository *repo, const char *path_packfile)
{
struct got_pack *pack = NULL;
size_t i;
for (i = 0; i < nitems(repo->packs); i++) {
pack = &repo->packs[i];
if (pack->path_packfile == NULL)
break;
if (strcmp(pack->path_packfile, path_packfile) == 0)
return pack;
}
return NULL;
}
const struct got_error *
got_repo_init(const char *repo_path)
{
const struct got_error *err = NULL;
const char *dirnames[] = {
GOT_OBJECTS_DIR,
GOT_OBJECTS_PACK_DIR,
GOT_REFS_DIR,
};
const char *description_str = "Unnamed repository; "
"edit this file 'description' to name the repository.";
const char *headref_str = "ref: refs/heads/main";
const char *gitconfig_str = "[core]\n"
"\trepositoryformatversion = 0\n"
"\tfilemode = true\n"
"\tbare = true\n";
char *path;
size_t i;
if (!got_path_dir_is_empty(repo_path))
return got_error(GOT_ERR_DIR_NOT_EMPTY);
for (i = 0; i < nitems(dirnames); i++) {
if (asprintf(&path, "%s/%s", repo_path, dirnames[i]) == -1) {
return got_error_from_errno("asprintf");
}
err = got_path_mkdir(path);
free(path);
if (err)
return err;
}
if (asprintf(&path, "%s/%s", repo_path, "description") == -1)
return got_error_from_errno("asprintf");
err = got_path_create_file(path, description_str);
free(path);
if (err)
return err;
if (asprintf(&path, "%s/%s", repo_path, GOT_HEAD_FILE) == -1)
return got_error_from_errno("asprintf");
err = got_path_create_file(path, headref_str);
free(path);
if (err)
return err;
if (asprintf(&path, "%s/%s", repo_path, "config") == -1)
return got_error_from_errno("asprintf");
err = got_path_create_file(path, gitconfig_str);
free(path);
if (err)
return err;
return NULL;
}
static const struct got_error *
match_packed_object(struct got_object_id **unique_id,
struct got_repository *repo, const char *id_str_prefix, int obj_type)
{
const struct got_error *err = NULL;
DIR *packdir = NULL;
struct dirent *dent;
char *path_packidx;
struct got_object_id_queue matched_ids;
int packdir_fd;
SIMPLEQ_INIT(&matched_ids);
packdir_fd = openat(got_repo_get_fd(repo),
GOT_OBJECTS_PACK_DIR, O_DIRECTORY);
if (packdir_fd == -1) {
if (errno != ENOENT)
err = got_error_from_errno2("openat", GOT_OBJECTS_PACK_DIR);
goto done;
}
packdir = fdopendir(packdir_fd);
if (packdir == NULL) {
err = got_error_from_errno("fdopendir");
goto done;
}
while ((dent = readdir(packdir)) != NULL) {
struct got_packidx *packidx;
struct got_object_qid *qid;
if (!is_packidx_filename(dent->d_name, strlen(dent->d_name)))
continue;
if (asprintf(&path_packidx, "%s/%s", GOT_OBJECTS_PACK_DIR,
dent->d_name) == -1) {
err = got_error_from_errno("strdup");
break;
}
err = got_packidx_open(&packidx, got_repo_get_fd(repo),
path_packidx, 0);
free(path_packidx);
if (err)
break;
err = got_packidx_match_id_str_prefix(&matched_ids,
packidx, id_str_prefix);
if (err) {
got_packidx_close(packidx);
break;
}
err = got_packidx_close(packidx);
if (err)
break;
SIMPLEQ_FOREACH(qid, &matched_ids, entry) {
if (obj_type != GOT_OBJ_TYPE_ANY) {
int matched_type;
err = got_object_get_type(&matched_type, repo,
qid->id);
if (err)
goto done;
if (matched_type != obj_type)
continue;
}
if (*unique_id == NULL) {
*unique_id = got_object_id_dup(qid->id);
if (*unique_id == NULL) {
err = got_error_from_errno("malloc");
goto done;
}
} else {
if (got_object_id_cmp(*unique_id, qid->id) == 0)
continue; /* packed multiple times */
err = got_error(GOT_ERR_AMBIGUOUS_ID);
goto done;
}
}
}
done:
got_object_id_queue_free(&matched_ids);
if (packdir && closedir(packdir) != 0 && err == NULL)
err = got_error_from_errno("closedir");
if (err) {
free(*unique_id);
*unique_id = NULL;
}
return err;
}
static const struct got_error *
match_loose_object(struct got_object_id **unique_id, const char *path_objects,
const char *object_dir, const char *id_str_prefix, int obj_type,
struct got_repository *repo)
{
const struct got_error *err = NULL;
char *path;
DIR *dir = NULL;
struct dirent *dent;
struct got_object_id id;
if (asprintf(&path, "%s/%s", path_objects, object_dir) == -1) {
err = got_error_from_errno("asprintf");
goto done;
}
dir = opendir(path);
if (dir == NULL) {
if (errno == ENOENT) {
err = NULL;
goto done;
}
err = got_error_from_errno2("opendir", path);
goto done;
}
while ((dent = readdir(dir)) != NULL) {
char *id_str;
int cmp;
if (strcmp(dent->d_name, ".") == 0 ||
strcmp(dent->d_name, "..") == 0)
continue;
if (asprintf(&id_str, "%s%s", object_dir, dent->d_name) == -1) {
err = got_error_from_errno("asprintf");
goto done;
}
if (!got_parse_sha1_digest(id.sha1, id_str))
continue;
/*
* Directory entries do not necessarily appear in
* sorted order, so we must iterate over all of them.
*/
cmp = strncmp(id_str, id_str_prefix, strlen(id_str_prefix));
if (cmp != 0) {
free(id_str);
continue;
}
if (*unique_id == NULL) {
if (obj_type != GOT_OBJ_TYPE_ANY) {
int matched_type;
err = got_object_get_type(&matched_type, repo,
&id);
if (err)
goto done;
if (matched_type != obj_type)
continue;
}
*unique_id = got_object_id_dup(&id);
if (*unique_id == NULL) {
err = got_error_from_errno("got_object_id_dup");
free(id_str);
goto done;
}
} else {
if (got_object_id_cmp(*unique_id, &id) == 0)
continue; /* both packed and loose */
err = got_error(GOT_ERR_AMBIGUOUS_ID);
free(id_str);
goto done;
}
}
done:
if (dir && closedir(dir) != 0 && err == NULL)
err = got_error_from_errno("closedir");
if (err) {
free(*unique_id);
*unique_id = NULL;
}
free(path);
return err;
}
const struct got_error *
got_repo_match_object_id_prefix(struct got_object_id **id,
const char *id_str_prefix, int obj_type, struct got_repository *repo)
{
const struct got_error *err = NULL;
char *path_objects = got_repo_get_path_objects(repo);
char *object_dir = NULL;
size_t len;
int i;
*id = NULL;
for (i = 0; i < strlen(id_str_prefix); i++) {
if (isxdigit((unsigned char)id_str_prefix[i]))
continue;
return got_error_path(id_str_prefix, GOT_ERR_BAD_OBJ_ID_STR);
}
len = strlen(id_str_prefix);
if (len >= 2) {
err = match_packed_object(id, repo, id_str_prefix, obj_type);
if (err)
goto done;
object_dir = strndup(id_str_prefix, 2);
if (object_dir == NULL) {
err = got_error_from_errno("strdup");
goto done;
}
err = match_loose_object(id, path_objects, object_dir,
id_str_prefix, obj_type, repo);
} else if (len == 1) {
int i;
for (i = 0; i < 0xf; i++) {
if (asprintf(&object_dir, "%s%.1x", id_str_prefix, i)
== -1) {
err = got_error_from_errno("asprintf");
goto done;
}
err = match_packed_object(id, repo, object_dir,
obj_type);
if (err)
goto done;
err = match_loose_object(id, path_objects, object_dir,
id_str_prefix, obj_type, repo);
if (err)
goto done;
}
} else {
err = got_error_path(id_str_prefix, GOT_ERR_BAD_OBJ_ID_STR);
goto done;
}
done:
free(object_dir);
if (err) {
free(*id);
*id = NULL;
} else if (*id == NULL)
err = got_error_path(id_str_prefix, GOT_ERR_NO_OBJ);
return err;
}
const struct got_error *
got_repo_match_object_id(struct got_object_id **id, char **label,
const char *id_str, int obj_type, struct got_reflist_head *refs,
struct got_repository *repo)
{
const struct got_error *err;
struct got_tag_object *tag;
struct got_reference *ref = NULL;
*id = NULL;
if (label)
*label = NULL;
if (refs) {
err = got_repo_object_match_tag(&tag, id_str, GOT_OBJ_TYPE_ANY,
refs, repo);
if (err == NULL) {
*id = got_object_id_dup(
got_object_tag_get_object_id(tag));
if (*id == NULL)
err = got_error_from_errno("got_object_id_dup");
else if (label && asprintf(label, "refs/tags/%s",
got_object_tag_get_name(tag)) == -1) {
err = got_error_from_errno("asprintf");
free(*id);
*id = NULL;
}
got_object_tag_close(tag);
return err;
} else if (err->code != GOT_ERR_OBJ_TYPE &&
err->code != GOT_ERR_NO_OBJ)
return err;
}
err = got_repo_match_object_id_prefix(id, id_str, obj_type, repo);
if (err) {
if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
return err;
err = got_ref_open(&ref, repo, id_str, 0);
if (err != NULL)
goto done;
if (label) {
*label = strdup(got_ref_get_name(ref));
if (*label == NULL) {
err = got_error_from_errno("strdup");
goto done;
}
}
err = got_ref_resolve(id, repo, ref);
} else if (label) {
err = got_object_id_str(label, *id);
if (*label == NULL) {
err = got_error_from_errno("strdup");
goto done;
}
}
done:
if (ref)
got_ref_close(ref);
return err;
}
const struct got_error *
got_repo_object_match_tag(struct got_tag_object **tag, const char *name,
int obj_type, struct got_reflist_head *refs, struct got_repository *repo)
{
const struct got_error *err = NULL;
struct got_reflist_entry *re;
struct got_object_id *tag_id;
int name_is_absolute = (strncmp(name, "refs/", 5) == 0);
*tag = NULL;
TAILQ_FOREACH(re, refs, entry) {
const char *refname;
refname = got_ref_get_name(re->ref);
if (got_ref_is_symbolic(re->ref))
continue;
if (strncmp(refname, "refs/tags/", 10) != 0)
continue;
if (!name_is_absolute)
refname += strlen("refs/tags/");
if (strcmp(refname, name) != 0)
continue;
err = got_ref_resolve(&tag_id, repo, re->ref);
if (err)
break;
err = got_object_open_as_tag(tag, repo, tag_id);
free(tag_id);
if (err)
break;
if (obj_type == GOT_OBJ_TYPE_ANY ||
got_object_tag_get_object_type(*tag) == obj_type)
break;
got_object_tag_close(*tag);
*tag = NULL;
}
if (err == NULL && *tag == NULL)
err = got_error_path(name, GOT_ERR_NO_OBJ);
return err;
}
static const struct got_error *
alloc_added_blob_tree_entry(struct got_tree_entry **new_te,
const char *name, mode_t mode, struct got_object_id *blob_id)
{
const struct got_error *err = NULL;
*new_te = NULL;
*new_te = calloc(1, sizeof(**new_te));
if (*new_te == NULL)
return got_error_from_errno("calloc");
if (strlcpy((*new_te)->name, name, sizeof((*new_te)->name)) >=
sizeof((*new_te)->name)) {
err = got_error(GOT_ERR_NO_SPACE);
goto done;
}
if (S_ISLNK(mode)) {
(*new_te)->mode = S_IFLNK;
} else {
(*new_te)->mode = S_IFREG;
(*new_te)->mode |= (mode & (S_IRWXU | S_IRWXG | S_IRWXO));
}
memcpy(&(*new_te)->id, blob_id, sizeof((*new_te)->id));
done:
if (err && *new_te) {
free(*new_te);
*new_te = NULL;
}
return err;
}
static const struct got_error *
import_file(struct got_tree_entry **new_te, struct dirent *de,
const char *path, struct got_repository *repo)
{
const struct got_error *err;
struct got_object_id *blob_id = NULL;
char *filepath;
struct stat sb;
if (asprintf(&filepath, "%s%s%s", path,
path[0] == '\0' ? "" : "/", de->d_name) == -1)
return got_error_from_errno("asprintf");
if (lstat(filepath, &sb) != 0) {
err = got_error_from_errno2("lstat", path);
goto done;
}
err = got_object_blob_create(&blob_id, filepath, repo);
if (err)
goto done;
err = alloc_added_blob_tree_entry(new_te, de->d_name, sb.st_mode,
blob_id);
done:
free(filepath);
if (err)
free(blob_id);
return err;
}
static const struct got_error *
insert_tree_entry(struct got_tree_entry *new_te,
struct got_pathlist_head *paths)
{
const struct got_error *err = NULL;
struct got_pathlist_entry *new_pe;
err = got_pathlist_insert(&new_pe, paths, new_te->name, new_te);
if (err)
return err;
if (new_pe == NULL)
return got_error(GOT_ERR_TREE_DUP_ENTRY);
return NULL;
}
static const struct got_error *write_tree(struct got_object_id **,
const char *, struct got_pathlist_head *, struct got_repository *,
got_repo_import_cb progress_cb, void *progress_arg);
static const struct got_error *
import_subdir(struct got_tree_entry **new_te, struct dirent *de,
const char *path, struct got_pathlist_head *ignores,
struct got_repository *repo,
got_repo_import_cb progress_cb, void *progress_arg)
{
const struct got_error *err;
struct got_object_id *id = NULL;
char *subdirpath;
if (asprintf(&subdirpath, "%s%s%s", path,
path[0] == '\0' ? "" : "/", de->d_name) == -1)
return got_error_from_errno("asprintf");
(*new_te) = calloc(1, sizeof(**new_te));
if (*new_te == NULL)
return got_error_from_errno("calloc");
(*new_te)->mode = S_IFDIR;
if (strlcpy((*new_te)->name, de->d_name, sizeof((*new_te)->name)) >=
sizeof((*new_te)->name)) {
err = got_error(GOT_ERR_NO_SPACE);
goto done;
}
err = write_tree(&id, subdirpath, ignores, repo,
progress_cb, progress_arg);
if (err)
goto done;
memcpy(&(*new_te)->id, id, sizeof((*new_te)->id));
done:
free(id);
free(subdirpath);
if (err) {
free(*new_te);
*new_te = NULL;
}
return err;
}
static const struct got_error *
write_tree(struct got_object_id **new_tree_id, const char *path_dir,
struct got_pathlist_head *ignores, struct got_repository *repo,
got_repo_import_cb progress_cb, void *progress_arg)
{
const struct got_error *err = NULL;
DIR *dir;
struct dirent *de;
int nentries;
struct got_tree_entry *new_te = NULL;
struct got_pathlist_head paths;
struct got_pathlist_entry *pe;
*new_tree_id = NULL;
TAILQ_INIT(&paths);
dir = opendir(path_dir);
if (dir == NULL) {
err = got_error_from_errno2("opendir", path_dir);
goto done;
}
nentries = 0;
while ((de = readdir(dir)) != NULL) {
int ignore = 0;
int type;
if (strcmp(de->d_name, ".") == 0 ||
strcmp(de->d_name, "..") == 0)
continue;
TAILQ_FOREACH(pe, ignores, entry) {
if (fnmatch(pe->path, de->d_name, 0) == 0) {
ignore = 1;
break;
}
}
if (ignore)
continue;
err = got_path_dirent_type(&type, path_dir, de);
if (err)
goto done;
if (type == DT_DIR) {
err = import_subdir(&new_te, de, path_dir,
ignores, repo, progress_cb, progress_arg);
if (err) {
if (err->code != GOT_ERR_NO_TREE_ENTRY)
goto done;
err = NULL;
continue;
}
} else if (type == DT_REG || type == DT_LNK) {
err = import_file(&new_te, de, path_dir, repo);
if (err)
goto done;
} else
continue;
err = insert_tree_entry(new_te, &paths);
if (err)
goto done;
nentries++;
}
if (TAILQ_EMPTY(&paths)) {
err = got_error_msg(GOT_ERR_NO_TREE_ENTRY,
"cannot create tree without any entries");
goto done;
}
TAILQ_FOREACH(pe, &paths, entry) {
struct got_tree_entry *te = pe->data;
char *path;
if (!S_ISREG(te->mode) && !S_ISLNK(te->mode))
continue;
if (asprintf(&path, "%s/%s", path_dir, pe->path) == -1) {
err = got_error_from_errno("asprintf");
goto done;
}
err = (*progress_cb)(progress_arg, path);
free(path);
if (err)
goto done;
}
err = got_object_tree_create(new_tree_id, &paths, nentries, repo);
done:
if (dir)
closedir(dir);
got_pathlist_free(&paths);
return err;
}
const struct got_error *
got_repo_import(struct got_object_id **new_commit_id, const char *path_dir,
const char *logmsg, const char *author, struct got_pathlist_head *ignores,
struct got_repository *repo, got_repo_import_cb progress_cb,
void *progress_arg)
{
const struct got_error *err;
struct got_object_id *new_tree_id;
err = write_tree(&new_tree_id, path_dir, ignores, repo,
progress_cb, progress_arg);
if (err)
return err;
err = got_object_commit_create(new_commit_id, new_tree_id, NULL, 0,
author, time(NULL), author, time(NULL), logmsg, repo);
free(new_tree_id);
return err;
}
|
ThomasAdam/gameoftrees
|
lib/fetch.c
|
<filename>lib/fetch.c<gh_stars>1-10
/*
* Copyright (c) 2018, 2019 <NAME> <<EMAIL>>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/uio.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <endian.h>
#include <errno.h>
#include <err.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <sha1.h>
#include <unistd.h>
#include <zlib.h>
#include <ctype.h>
#include <limits.h>
#include <time.h>
#include <uuid.h>
#include <netdb.h>
#include <netinet/in.h>
#include "got_error.h"
#include "got_reference.h"
#include "got_repository.h"
#include "got_path.h"
#include "got_cancel.h"
#include "got_worktree.h"
#include "got_object.h"
#include "got_opentemp.h"
#include "got_fetch.h"
#include "got_lib_delta.h"
#include "got_lib_inflate.h"
#include "got_lib_object.h"
#include "got_lib_object_parse.h"
#include "got_lib_object_create.h"
#include "got_lib_pack.h"
#include "got_lib_sha1.h"
#include "got_lib_privsep.h"
#include "got_lib_object_cache.h"
#include "got_lib_repository.h"
#ifndef nitems
#define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
#endif
#ifndef ssizeof
#define ssizeof(_x) ((ssize_t)(sizeof(_x)))
#endif
#ifndef MIN
#define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
#endif
static int
hassuffix(char *base, char *suf)
{
int nb, ns;
nb = strlen(base);
ns = strlen(suf);
if (ns <= nb && strcmp(base + (nb - ns), suf) == 0)
return 1;
return 0;
}
static const struct got_error *
dial_ssh(pid_t *fetchpid, int *fetchfd, const char *host, const char *port,
const char *path, const char *direction, int verbosity)
{
const struct got_error *error = NULL;
int pid, pfd[2];
char cmd[64];
char *argv[11];
int i = 0, j;
*fetchpid = -1;
*fetchfd = -1;
argv[i++] = GOT_FETCH_PATH_SSH;
if (port != NULL) {
argv[i++] = "-p";
argv[i++] = (char *)port;
}
if (verbosity == -1) {
argv[i++] = "-q";
} else {
/* ssh(1) allows up to 3 "-v" options. */
for (j = 0; j < MIN(3, verbosity); j++)
argv[i++] = "-v";
}
argv[i++] = "--";
argv[i++] = (char *)host;
argv[i++] = (char *)cmd;
argv[i++] = (char *)path;
argv[i++] = NULL;
if (pipe(pfd) == -1)
return got_error_from_errno("pipe");
pid = fork();
if (pid == -1) {
error = got_error_from_errno("fork");
close(pfd[0]);
close(pfd[1]);
return error;
} else if (pid == 0) {
int n;
close(pfd[1]);
dup2(pfd[0], 0);
dup2(pfd[0], 1);
n = snprintf(cmd, sizeof(cmd), "git-%s-pack", direction);
if (n < 0 || n >= ssizeof(cmd))
err(1, "snprintf");
if (execv(GOT_FETCH_PATH_SSH, argv) == -1)
err(1, "execl");
abort(); /* not reached */
} else {
close(pfd[0]);
*fetchpid = pid;
*fetchfd = pfd[1];
return NULL;
}
}
static const struct got_error *
dial_git(int *fetchfd, const char *host, const char *port, const char *path,
const char *direction)
{
const struct got_error *err = NULL;
struct addrinfo hints, *servinfo, *p;
char *cmd = NULL, *pkt = NULL;
int fd = -1, totlen, r, eaicode;
*fetchfd = -1;
if (port == NULL)
port = GOT_DEFAULT_GIT_PORT_STR;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
eaicode = getaddrinfo(host, port, &hints, &servinfo);
if (eaicode) {
char msg[512];
snprintf(msg, sizeof(msg), "%s: %s", host,
gai_strerror(eaicode));
return got_error_msg(GOT_ERR_ADDRINFO, msg);
}
for (p = servinfo; p != NULL; p = p->ai_next) {
if ((fd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1)
continue;
if (connect(fd, p->ai_addr, p->ai_addrlen) == 0) {
err = NULL;
break;
}
err = got_error_from_errno("connect");
close(fd);
}
if (p == NULL)
goto done;
if (asprintf(&cmd, "git-%s-pack %s", direction, path) == -1) {
err = got_error_from_errno("asprintf");
goto done;
}
totlen = 4 + strlen(cmd) + 1 + strlen("host=") + strlen(host) + 1;
if (asprintf(&pkt, "%04x%s", totlen, cmd) == -1) {
err = got_error_from_errno("asprintf");
goto done;
}
r = write(fd, pkt, strlen(pkt) + 1);
if (r == -1) {
err = got_error_from_errno("write");
goto done;
}
if (asprintf(&pkt, "host=%s", host) == -1) {
err = got_error_from_errno("asprintf");
goto done;
}
r = write(fd, pkt, strlen(pkt) + 1);
if (r == -1) {
err = got_error_from_errno("write");
goto done;
}
done:
free(cmd);
free(pkt);
if (err) {
if (fd != -1)
close(fd);
} else
*fetchfd = fd;
return err;
}
const struct got_error *
got_fetch_connect(pid_t *fetchpid, int *fetchfd, const char *proto,
const char *host, const char *port, const char *server_path, int verbosity)
{
const struct got_error *err = NULL;
*fetchpid = -1;
*fetchfd = -1;
if (strcmp(proto, "ssh") == 0 || strcmp(proto, "git+ssh") == 0)
err = dial_ssh(fetchpid, fetchfd, host, port, server_path,
"upload", verbosity);
else if (strcmp(proto, "git") == 0)
err = dial_git(fetchfd, host, port, server_path, "upload");
else if (strcmp(proto, "http") == 0 || strcmp(proto, "git+http") == 0)
err = got_error_path(proto, GOT_ERR_NOT_IMPL);
else
err = got_error_path(proto, GOT_ERR_BAD_PROTO);
return err;
}
const struct got_error *
got_fetch_parse_uri(char **proto, char **host, char **port,
char **server_path, char **repo_name, const char *uri)
{
const struct got_error *err = NULL;
char *s, *p, *q;
int n;
*proto = *host = *port = *server_path = *repo_name = NULL;
p = strstr(uri, "://");
if (!p) {
/* Try parsing Git's "scp" style URL syntax. */
*proto = strdup("ssh");
if (proto == NULL) {
err = got_error_from_errno("strdup");
goto done;
}
s = (char *)uri;
q = strchr(s, ':');
if (q == NULL) {
err = got_error(GOT_ERR_PARSE_URI);
goto done;
}
/* No slashes allowed before first colon. */
p = strchr(s, '/');
if (p && q > p) {
err = got_error(GOT_ERR_PARSE_URI);
goto done;
}
*host = strndup(s, q - s);
if (*host == NULL) {
err = got_error_from_errno("strndup");
goto done;
}
p = q + 1;
} else {
*proto = strndup(uri, p - uri);
if (proto == NULL) {
err = got_error_from_errno("strndup");
goto done;
}
s = p + 3;
p = strstr(s, "/");
if (p == NULL || strlen(p) == 1) {
err = got_error(GOT_ERR_PARSE_URI);
goto done;
}
q = memchr(s, ':', p - s);
if (q) {
*host = strndup(s, q - s);
if (*host == NULL) {
err = got_error_from_errno("strndup");
goto done;
}
*port = strndup(q + 1, p - (q + 1));
if (*port == NULL) {
err = got_error_from_errno("strndup");
goto done;
}
} else {
*host = strndup(s, p - s);
if (*host == NULL) {
err = got_error_from_errno("strndup");
goto done;
}
}
}
while (p[0] == '/' && p[1] == '/')
p++;
*server_path = strdup(p);
if (*server_path == NULL) {
err = got_error_from_errno("strdup");
goto done;
}
got_path_strip_trailing_slashes(*server_path);
p = strrchr(p, '/');
if (!p || strlen(p) <= 1) {
err = got_error(GOT_ERR_PARSE_URI);
goto done;
}
p++;
n = strlen(p);
if (n == 0) {
err = got_error(GOT_ERR_PARSE_URI);
goto done;
}
if (hassuffix(p, ".git"))
n -= 4;
*repo_name = strndup(p, (p + n) - p);
if (*repo_name == NULL) {
err = got_error_from_errno("strndup");
goto done;
}
done:
if (err) {
free(*proto);
*proto = NULL;
free(*host);
*host = NULL;
free(*port);
*port = NULL;
free(*server_path);
*server_path = NULL;
free(*repo_name);
*repo_name = NULL;
}
return err;
}
const struct got_error*
got_fetch_pack(struct got_object_id **pack_hash, struct got_pathlist_head *refs,
struct got_pathlist_head *symrefs, const char *remote_name,
int mirror_references, int fetch_all_branches,
struct got_pathlist_head *wanted_branches,
struct got_pathlist_head *wanted_refs, int list_refs_only, int verbosity,
int fetchfd, struct got_repository *repo,
got_fetch_progress_cb progress_cb, void *progress_arg)
{
size_t i;
int imsg_fetchfds[2], imsg_idxfds[2];
int packfd = -1, npackfd = -1, idxfd = -1, nidxfd = -1, nfetchfd = -1;
int tmpfds[3];
int fetchstatus, idxstatus, done = 0;
const struct got_error *err;
struct imsgbuf fetchibuf, idxibuf;
pid_t fetchpid, idxpid;
char *tmppackpath = NULL, *tmpidxpath = NULL;
char *packpath = NULL, *idxpath = NULL, *id_str = NULL;
const char *repo_path = NULL;
struct got_pathlist_head have_refs;
struct got_pathlist_entry *pe;
struct got_reflist_head my_refs;
struct got_reflist_entry *re;
off_t packfile_size = 0;
struct got_packfile_hdr pack_hdr;
uint32_t nobj = 0;
char *ref_prefix = NULL;
size_t ref_prefixlen = 0;
char *path;
char *progress = NULL;
*pack_hash = NULL;
/*
* Prevent fetching of references that won't make any
* sense outside of the remote repository's context.
*/
TAILQ_FOREACH(pe, wanted_refs, entry) {
const char *refname = pe->path;
if (strncmp(refname, "refs/got/", 9) == 0 ||
strncmp(refname, "got/", 4) == 0 ||
strncmp(refname, "refs/remotes/", 13) == 0 ||
strncmp(refname, "remotes/", 8) == 0)
return got_error_path(refname, GOT_ERR_FETCH_BAD_REF);
}
if (!list_refs_only)
repo_path = got_repo_get_path_git_dir(repo);
for (i = 0; i < nitems(tmpfds); i++)
tmpfds[i] = -1;
TAILQ_INIT(&have_refs);
TAILQ_INIT(&my_refs);
if (!mirror_references) {
if (asprintf(&ref_prefix, "refs/remotes/%s/",
remote_name) == -1)
return got_error_from_errno("asprintf");
ref_prefixlen = strlen(ref_prefix);
}
if (!list_refs_only) {
err = got_ref_list(&my_refs, repo, NULL,
got_ref_cmp_by_name, NULL);
if (err)
goto done;
}
TAILQ_FOREACH(re, &my_refs, entry) {
struct got_object_id *id;
const char *refname;
if (got_ref_is_symbolic(re->ref))
continue;
refname = got_ref_get_name(re->ref);
if (mirror_references) {
char *name;
err = got_ref_resolve(&id, repo, re->ref);
if (err)
goto done;
name = strdup(refname);
if (name == NULL) {
err = got_error_from_errno("strdup");
goto done;
}
err = got_pathlist_append(&have_refs, name, id);
if (err)
goto done;
continue;
}
if (strncmp("refs/tags/", refname, 10) == 0) {
char *tagname;
err = got_ref_resolve(&id, repo, re->ref);
if (err)
goto done;
tagname = strdup(refname);
if (tagname == NULL) {
err = got_error_from_errno("strdup");
goto done;
}
err = got_pathlist_append(&have_refs, tagname, id);
if (err) {
free(tagname);
goto done;
}
}
if (strncmp(ref_prefix, refname, ref_prefixlen) == 0) {
char *branchname;
err = got_ref_resolve(&id, repo, re->ref);
if (err)
goto done;
if (asprintf(&branchname, "refs/heads/%s",
refname + ref_prefixlen) == -1) {
err = got_error_from_errno("asprintf");
goto done;
}
err = got_pathlist_append(&have_refs, branchname, id);
if (err) {
free(branchname);
goto done;
}
}
}
if (list_refs_only) {
packfd = got_opentempfd();
if (packfd == -1) {
err = got_error_from_errno("got_opentempfd");
goto done;
}
} else {
if (asprintf(&path, "%s/%s/fetching.pack",
repo_path, GOT_OBJECTS_PACK_DIR) == -1) {
err = got_error_from_errno("asprintf");
goto done;
}
err = got_opentemp_named_fd(&tmppackpath, &packfd, path);
free(path);
if (err)
goto done;
if (fchmod(packfd, GOT_DEFAULT_FILE_MODE) != 0) {
err = got_error_from_errno2("fchmod", tmppackpath);
goto done;
}
}
if (list_refs_only) {
idxfd = got_opentempfd();
if (idxfd == -1) {
err = got_error_from_errno("got_opentempfd");
goto done;
}
} else {
if (asprintf(&path, "%s/%s/fetching.idx",
repo_path, GOT_OBJECTS_PACK_DIR) == -1) {
err = got_error_from_errno("asprintf");
goto done;
}
err = got_opentemp_named_fd(&tmpidxpath, &idxfd, path);
free(path);
if (err)
goto done;
if (fchmod(idxfd, GOT_DEFAULT_FILE_MODE) != 0) {
err = got_error_from_errno2("fchmod", tmpidxpath);
goto done;
}
}
nidxfd = dup(idxfd);
if (nidxfd == -1) {
err = got_error_from_errno("dup");
goto done;
}
for (i = 0; i < nitems(tmpfds); i++) {
tmpfds[i] = got_opentempfd();
if (tmpfds[i] == -1) {
err = got_error_from_errno("got_opentempfd");
goto done;
}
}
if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, imsg_fetchfds) == -1) {
err = got_error_from_errno("socketpair");
goto done;
}
fetchpid = fork();
if (fetchpid == -1) {
err = got_error_from_errno("fork");
goto done;
} else if (fetchpid == 0){
got_privsep_exec_child(imsg_fetchfds,
GOT_PATH_PROG_FETCH_PACK, tmppackpath);
}
if (close(imsg_fetchfds[1]) != 0) {
err = got_error_from_errno("close");
goto done;
}
imsg_init(&fetchibuf, imsg_fetchfds[0]);
nfetchfd = dup(fetchfd);
if (nfetchfd == -1) {
err = got_error_from_errno("dup");
goto done;
}
err = got_privsep_send_fetch_req(&fetchibuf, nfetchfd, &have_refs,
fetch_all_branches, wanted_branches, wanted_refs,
list_refs_only, verbosity);
if (err != NULL)
goto done;
nfetchfd = -1;
npackfd = dup(packfd);
if (npackfd == -1) {
err = got_error_from_errno("dup");
goto done;
}
err = got_privsep_send_fetch_outfd(&fetchibuf, npackfd);
if (err != NULL)
goto done;
npackfd = -1;
packfile_size = 0;
progress = calloc(GOT_FETCH_PKTMAX, 1);
if (progress == NULL) {
err = got_error_from_errno("calloc");
goto done;
}
*pack_hash = calloc(1, sizeof(**pack_hash));
if (*pack_hash == NULL) {
err = got_error_from_errno("calloc");
goto done;
}
while (!done) {
struct got_object_id *id = NULL;
char *refname = NULL;
char *server_progress = NULL;
off_t packfile_size_cur = 0;
err = got_privsep_recv_fetch_progress(&done,
&id, &refname, symrefs, &server_progress,
&packfile_size_cur, (*pack_hash)->sha1, &fetchibuf);
if (err != NULL)
goto done;
if (!done && refname && id) {
err = got_pathlist_insert(NULL, refs, refname, id);
if (err)
goto done;
} else if (!done && server_progress) {
char *p;
/*
* XXX git-daemon tends to send batched output with
* lines spanning separate packets. Buffer progress
* output until we see a CR or LF to avoid giving
* partial lines of progress output to the callback.
*/
if (strlcat(progress, server_progress,
GOT_FETCH_PKTMAX) >= GOT_FETCH_PKTMAX) {
progress[0] = '\0'; /* discard */
continue;
}
while ((p = strchr(progress, '\r')) != NULL ||
(p = strchr(progress, '\n')) != NULL) {
char *s;
size_t n;
char c = *p;
*p = '\0';
if (asprintf(&s, "%s%s", progress,
c == '\n' ? "\n" : "") == -1) {
err = got_error_from_errno("asprintf");
goto done;
}
err = progress_cb(progress_arg, s,
packfile_size_cur, 0, 0, 0, 0);
free(s);
if (err)
break;
n = strlen(progress);
if (n < GOT_FETCH_PKTMAX - 1) {
memmove(progress, &progress[n + 1],
GOT_FETCH_PKTMAX - n - 1);
} else
progress[0] = '\0';
}
free(server_progress);
if (err)
goto done;
} else if (!done && packfile_size_cur != packfile_size) {
err = progress_cb(progress_arg, NULL,
packfile_size_cur, 0, 0, 0, 0);
if (err)
break;
packfile_size = packfile_size_cur;
}
}
if (waitpid(fetchpid, &fetchstatus, 0) == -1) {
err = got_error_from_errno("waitpid");
goto done;
}
if (lseek(packfd, 0, SEEK_SET) == -1) {
err = got_error_from_errno("lseek");
goto done;
}
/* If zero data was fetched without error we are already up-to-date. */
if (packfile_size == 0) {
free(*pack_hash);
*pack_hash = NULL;
goto done;
} else if (packfile_size < ssizeof(pack_hdr) + SHA1_DIGEST_LENGTH) {
err = got_error_msg(GOT_ERR_BAD_PACKFILE, "short pack file");
goto done;
} else {
ssize_t n;
n = read(packfd, &pack_hdr, ssizeof(pack_hdr));
if (n == -1) {
err = got_error_from_errno("read");
goto done;
}
if (n != ssizeof(pack_hdr)) {
err = got_error(GOT_ERR_IO);
goto done;
}
if (pack_hdr.signature != htobe32(GOT_PACKFILE_SIGNATURE)) {
err = got_error_msg(GOT_ERR_BAD_PACKFILE,
"bad pack file signature");
goto done;
}
if (pack_hdr.version != htobe32(GOT_PACKFILE_VERSION)) {
err = got_error_msg(GOT_ERR_BAD_PACKFILE,
"bad pack file version");
goto done;
}
nobj = be32toh(pack_hdr.nobjects);
if (nobj == 0 &&
packfile_size > ssizeof(pack_hdr) + SHA1_DIGEST_LENGTH)
return got_error_msg(GOT_ERR_BAD_PACKFILE,
"bad pack file with zero objects");
if (nobj != 0 &&
packfile_size <= ssizeof(pack_hdr) + SHA1_DIGEST_LENGTH)
return got_error_msg(GOT_ERR_BAD_PACKFILE,
"empty pack file with non-zero object count");
}
/*
* If the pack file contains no objects, we may only need to update
* references in our repository. The caller will take care of that.
*/
if (nobj == 0)
goto done;
if (lseek(packfd, 0, SEEK_SET) == -1) {
err = got_error_from_errno("lseek");
goto done;
}
if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, imsg_idxfds) == -1) {
err = got_error_from_errno("socketpair");
goto done;
}
idxpid = fork();
if (idxpid == -1) {
err= got_error_from_errno("fork");
goto done;
} else if (idxpid == 0)
got_privsep_exec_child(imsg_idxfds,
GOT_PATH_PROG_INDEX_PACK, tmppackpath);
if (close(imsg_idxfds[1]) != 0) {
err = got_error_from_errno("close");
goto done;
}
imsg_init(&idxibuf, imsg_idxfds[0]);
npackfd = dup(packfd);
if (npackfd == -1) {
err = got_error_from_errno("dup");
goto done;
}
err = got_privsep_send_index_pack_req(&idxibuf, (*pack_hash)->sha1,
npackfd);
if (err != NULL)
goto done;
npackfd = -1;
err = got_privsep_send_index_pack_outfd(&idxibuf, nidxfd);
if (err != NULL)
goto done;
nidxfd = -1;
for (i = 0; i < nitems(tmpfds); i++) {
err = got_privsep_send_tmpfd(&idxibuf, tmpfds[i]);
if (err != NULL)
goto done;
tmpfds[i] = -1;
}
done = 0;
while (!done) {
int nobj_total, nobj_indexed, nobj_loose, nobj_resolved;
err = got_privsep_recv_index_progress(&done, &nobj_total,
&nobj_indexed, &nobj_loose, &nobj_resolved,
&idxibuf);
if (err != NULL)
goto done;
if (nobj_indexed != 0) {
err = progress_cb(progress_arg, NULL,
packfile_size, nobj_total,
nobj_indexed, nobj_loose, nobj_resolved);
if (err)
break;
}
imsg_clear(&idxibuf);
}
if (close(imsg_idxfds[0]) == -1) {
err = got_error_from_errno("close");
goto done;
}
if (waitpid(idxpid, &idxstatus, 0) == -1) {
err = got_error_from_errno("waitpid");
goto done;
}
err = got_object_id_str(&id_str, *pack_hash);
if (err)
goto done;
if (asprintf(&packpath, "%s/%s/pack-%s.pack",
repo_path, GOT_OBJECTS_PACK_DIR, id_str) == -1) {
err = got_error_from_errno("asprintf");
goto done;
}
if (asprintf(&idxpath, "%s/%s/pack-%s.idx",
repo_path, GOT_OBJECTS_PACK_DIR, id_str) == -1) {
err = got_error_from_errno("asprintf");
goto done;
}
if (rename(tmppackpath, packpath) == -1) {
err = got_error_from_errno3("rename", tmppackpath, packpath);
goto done;
}
free(tmppackpath);
tmppackpath = NULL;
if (rename(tmpidxpath, idxpath) == -1) {
err = got_error_from_errno3("rename", tmpidxpath, idxpath);
goto done;
}
free(tmpidxpath);
tmpidxpath = NULL;
done:
if (tmppackpath && unlink(tmppackpath) == -1 && err == NULL)
err = got_error_from_errno2("unlink", tmppackpath);
if (tmpidxpath && unlink(tmpidxpath) == -1 && err == NULL)
err = got_error_from_errno2("unlink", tmpidxpath);
if (nfetchfd != -1 && close(nfetchfd) == -1 && err == NULL)
err = got_error_from_errno("close");
if (npackfd != -1 && close(npackfd) == -1 && err == NULL)
err = got_error_from_errno("close");
if (packfd != -1 && close(packfd) == -1 && err == NULL)
err = got_error_from_errno("close");
if (idxfd != -1 && close(idxfd) == -1 && err == NULL)
err = got_error_from_errno("close");
for (i = 0; i < nitems(tmpfds); i++) {
if (tmpfds[i] != -1 && close(tmpfds[i]) == -1 && err == NULL)
err = got_error_from_errno("close");
}
free(tmppackpath);
free(tmpidxpath);
free(idxpath);
free(packpath);
free(ref_prefix);
free(progress);
TAILQ_FOREACH(pe, &have_refs, entry) {
free((char *)pe->path);
free(pe->data);
}
got_pathlist_free(&have_refs);
got_ref_list_free(&my_refs);
if (err) {
free(*pack_hash);
*pack_hash = NULL;
TAILQ_FOREACH(pe, refs, entry) {
free((void *)pe->path);
free(pe->data);
}
got_pathlist_free(refs);
TAILQ_FOREACH(pe, symrefs, entry) {
free((void *)pe->path);
free(pe->data);
}
got_pathlist_free(symrefs);
}
return err;
}
|
ayoubboum/share_image_socially
|
ios/Classes/ShareImageSociallyPlugin.h
|
#import <Flutter/Flutter.h>
@interface ShareImageSociallyPlugin : NSObject<FlutterPlugin>
@end
|
simo-andreev/Emotion
|
Emotion/Assets/Shaders/GetTextureSize.c
|
<filename>Emotion/Assets/Shaders/GetTextureSize.c
#define getTextureSize(sampler) textureSize(sampler, 0)
|
simo-andreev/Emotion
|
Emotion/Assets/Shaders/GetTextureColor.c
|
#define getTextureColor(sampler, uv) texture(sampler, uv)
|
nebososo/uzebox-patch-converter
|
input.h
|
bool read_patches(const char *fn,
std::map<std::string, std::vector<uint8_t>> &data);
|
nebososo/uzebox-patch-converter
|
step_table.h
|
<gh_stars>1-10
const int step_table[] = {
0x0022, 0x0024, 0x0026, 0x0028, 0x002b, 0x002d, 0x0030, 0x0033, 0x0036,
0x0039, 0x003d, 0x0040, 0x0044, 0x0048, 0x004c, 0x0051, 0x0056, 0x005b,
0x0060, 0x0066, 0x006c, 0x0073, 0x0079, 0x0081, 0x0088, 0x0090, 0x0099,
0x00a2, 0x00ac, 0x00b6, 0x00c1, 0x00cc, 0x00d8, 0x00e5, 0x00f3, 0x0101,
0x0110, 0x0121, 0x0132, 0x0144, 0x0157, 0x016c, 0x0181, 0x0198, 0x01b0,
0x01ca, 0x01e5, 0x0202, 0x0221, 0x0241, 0x0264, 0x0288, 0x02ae, 0x02d7,
0x0303, 0x0330, 0x0361, 0x0394, 0x03cb, 0x0405, 0x0442, 0x0483, 0x04c7,
0x0510, 0x055d, 0x05af, 0x0605, 0x0661, 0x06c2, 0x0729, 0x0796, 0x0809,
0x0883, 0x0905, 0x098e, 0x0a20, 0x0aba, 0x0b5d, 0x0c0a, 0x0cc1, 0x0d84,
0x0e51, 0x0f2b, 0x1012, 0x1107, 0x120a, 0x131d, 0x1440, 0x1574, 0x16ba,
0x1814, 0x1983, 0x1b07, 0x1ca3, 0x1e57, 0x2024, 0x220e, 0x2414, 0x2639,
0x287f, 0x2ae8, 0x2d75, 0x3029, 0x3306, 0x360f, 0x3945, 0x3cad, 0x4049,
0x441b, 0x4828, 0x4c73, 0x50fe, 0x55cf, 0x5aea, 0x6051, 0x660c, 0x6c1d,
0x728b, 0x795a, 0x8092, 0x8837, 0x9050, 0x98e5, 0xa1fd, 0xab9f, 0xb5d3,
0xc0a3
};
|
nebososo/uzebox-patch-converter
|
generate.h
|
#define SAMPLE_RATE 15734
#define SAMPLES_PER_FRAME ((SAMPLE_RATE)/60)
#define DEFAULT_VOLUME 0xc0
#define PC_ENV_SPEED 0
#define PC_NOISE_PARAMS 1
#define PC_WAVE 2
#define PC_NOTE_UP 3
#define PC_NOTE_DOWN 4
#define PC_NOTE_CUT 5
#define PC_NOTE_HOLD 6
#define PC_ENV_VOL 7
#define PC_PITCH 8
#define PC_TREMOLO_LEVEL 9
#define PC_TREMOLO_RATE 10
#define PC_SLIDE 11
#define PC_SLIDE_SPEED 12
#define PC_LOOP_START 13
#define PC_LOOP_END 14
#define PATCH_END 0xff
bool write_wave(const char *fn, const std::vector<int8_t> &data);
bool generate_wave(const std::vector<uint8_t> &patch,
std::vector<int8_t> &data);
|
k-ishigaki/Linesensor2017
|
src/hardware/TimerModule.c
|
<reponame>k-ishigaki/Linesensor2017
#include <xc.h>
#include "Hardware.h"
#ifndef DECLARED_ONCE
#define DECLARED_ONCE
// ----------------------------------------------------------------------------
// Timer0Module_Constants
// ----------------------------------------------------------------------------
enum Timer0Module_ClockSource_Constants {
T0_T0CKI = 0b01,
T0_CPSCLK = 0b11,
T0_F_OSC_DIV_4 = 0b00,
};
const struct Timer0Module_ClockSource Timer0Module_ClockSource = {
T0_T0CKI,
T0_CPSCLK,
T0_F_OSC_DIV_4,
};
enum Timer0Module_Prescaler_Constants {
T0_RATE_1_1,
T0_RATE_1_2 = 0b000,
T0_RATE_1_4 = 0b001,
T0_RATE_1_8 = 0b010,
T0_RATE_1_16 = 0b011,
T0_RATE_1_32 = 0b100,
T0_RATE_1_64 = 0b101,
T0_RATE_1_128 = 0b110,
T0_RATE_1_256 = 0b111,
};
const struct Timer0Module_Prescaler Timer0Module_Prescaler = {
T0_RATE_1_1,
T0_RATE_1_2,
T0_RATE_1_4,
T0_RATE_1_8,
T0_RATE_1_16,
T0_RATE_1_32,
T0_RATE_1_64,
T0_RATE_1_128,
T0_RATE_1_256,
};
// ----------------------------------------------------------------------------
// Timer0Module
// ----------------------------------------------------------------------------
static uint16_t Timer0Module_getCount() {
return TMR0;
}
static void Timer0Module_setCount(uint16_t count) {
// note:
// When TMR0 is written, the increment is inhibited for
// two instruction cycles immediately following the write
TMR0 = count;
}
static void Timer0Module_start() {
// timer0 module is always enabled
}
static void Timer0Module_stop() {
// timer0 module is always enabled
}
static const TimerModule Timer0Module_instance = {
Timer0Module_getCount,
Timer0Module_setCount,
Timer0Module_start,
Timer0Module_stop,
};
const TimerModule* Timer0Module_constructor(
char clockSource,
char prescaler) {
// decide clock source
CPSCON0bits.T0XCS = clockSource;
OPTION_REGbits.TMR0CS = clockSource >> 1;
// decide prescaler
if(prescaler == T0_RATE_1_1) {
OPTION_REGbits.PSA = 1;
} else {
OPTION_REGbits.PSA = 0;
OPTION_REGbits.PS = prescaler;
}
return &Timer0Module_instance;
}
// ----------------------------------------------------------------------------
// Timer1Module_Constants
// ----------------------------------------------------------------------------
enum Timer1Module_ClockSource_Constants {
T1_T1OSC_SYNC = 0b0110,
T1_T1OSC_NOT_SYNC = 0b1110,
T1_CPSCLK_SYNC = 0b0011,
T1_CPSCLK_NOT_SYNC = 0b1011,
T1_T1CKI_SYNC = 0b0010,
T1_T1CKI_NOT_SYNC = 0b1010,
T1_F_OSC = 0b0001,
T1_F_OSC_DIV_4 = 0b0000,
};
const struct Timer1Module_ClockSource Timer1Module_ClockSource = {
T1_T1OSC_SYNC,
T1_T1OSC_NOT_SYNC,
T1_CPSCLK_SYNC,
T1_CPSCLK_NOT_SYNC,
T1_T1CKI_SYNC,
T1_T1CKI_NOT_SYNC,
T1_F_OSC,
T1_F_OSC_DIV_4,
};
enum Timer1Module_Prescaler_Constants {
T1_RATE_1_1 = 0b00,
T1_RATE_1_2 = 0b01,
T1_RATE_1_4 = 0b10,
T1_RATE_1_8 = 0b11,
};
const struct Timer1Module_Prescaler Timer1Module_Prescaler = {
T1_RATE_1_1,
T1_RATE_1_2,
T1_RATE_1_4,
T1_RATE_1_8,
};
// ----------------------------------------------------------------------------
// Timer1Module
// ----------------------------------------------------------------------------
static uint16_t Timer1Module_getCount() {
// 16bit read/write mode is not available (pic16f)
// so it is recommended to stop timer before read count
bool state = T1CONbits.TMR1ON;
T1CONbits.TMR1ON = 0;
uint16_t count = ((uint16_t)TMR1H << 8) + TMR1L;
T1CONbits.TMR1ON = state;
return count;
}
static void Timer1Module_setCount(uint16_t count) {
// 16bit read/write mode is not available (pic16f)
// so it is recommended to stop timer before write count
bool state = T1CONbits.TMR1ON;
T1CONbits.TMR1ON = 0;
TMR1H = count >> 8;
TMR1L = count;
T1CONbits.TMR1ON = state;
}
static void Timer1Module_start() {
T1CONbits.TMR1ON = 1;
}
static void Timer1Module_stop() {
T1CONbits.TMR1ON = 0;
}
static const TimerModule Timer1Module_instance = {
Timer1Module_getCount,
Timer1Module_setCount,
Timer1Module_start,
Timer1Module_stop,
};
const TimerModule* Timer1Module_constructor(
char clockSource,
char prescaler) {
// decide clock source
T1CONbits.TMR1CS = clockSource;
T1CONbits.T1OSCEN = clockSource >> 2;
T1CONbits.nT1SYNC = clockSource >> 3;
// decide prescaler
T1CONbits.T1CKPS = prescaler;
return &Timer1Module_instance;
}
// ----------------------------------------------------------------------------
// Timer1GateControl_Constants
// ----------------------------------------------------------------------------
enum Timer1GateControl_Source_Constants {
T1G_T1G = 0b00,
T1G_TIMER0_OVERFLOW = 0b01,
T1G_SYNC_C1OUT = 0b10,
T1G_SYNC_C2OUT = 0b11,
};
const struct Timer1GateControl_Source Timer1GateControl_Source = {
T1G_T1G,
T1G_TIMER0_OVERFLOW,
T1G_SYNC_C1OUT,
T1G_SYNC_C2OUT,
};
enum Timer1GateControl_Mode_Constants {
ENABLE_POSITIVE = 0b100,
ENABLE_NEGATIVE = 0b000,
TOGGLE_POSITIVE = 0b110,
TOGGLE_NEGATIVE = 0b010,
SINGLE_PULSE_POSITIVE = 0b101,
SINGLE_PULSE_NEGATIVE = 0b001,
TOGGLE_AND_SINGLE_PULSE_POSITIVE = 0b111,
TOGGLE_AND_SINGLE_PULSE_NEGATIVE = 0b011,
};
const struct Timer1GateControl_Mode Timer1GateControl = {
ENABLE_POSITIVE,
ENABLE_NEGATIVE,
TOGGLE_POSITIVE,
TOGGLE_NEGATIVE,
SINGLE_PULSE_POSITIVE,
SINGLE_PULSE_NEGATIVE,
TOGGLE_AND_SINGLE_PULSE_POSITIVE,
TOGGLE_AND_SINGLE_PULSE_NEGATIVE,
};
// ----------------------------------------------------------------------------
// Timer1GateControl
// ----------------------------------------------------------------------------
static bool Timer1GateControl_getState() {
return T1GCONbits.T1GVAL;
}
static void Timer1GateControl_startSinglePulseAquisition() {
T1GCONbits.T1GGO = 1;
}
static bool Timer1GateControl_isWaitingSinglePulse() {
return T1GCONbits.T1GGO;
}
static const TimerGateControl Timer1GateControl_instance = {
Timer1GateControl_getState,
Timer1GateControl_startSinglePulseAquisition,
Timer1GateControl_isWaitingSinglePulse,
};
const TimerGateControl* Timer1GateControl_constructor(
char source,
char mode) {
T1GCONbits.T1GSS = source;
T1GCONbits.T1GPOL = mode >> 2;
T1GCONbits.T1GTM = mode >> 1;
T1GCONbits.T1GSPM = mode;
T1GCONbits.TMR1GE = 1;
return &Timer1GateControl_instance;
}
void Timer1GateControl_destructor() {
T1GCONbits.TMR1GE = 0;
}
// ----------------------------------------------------------------------------
// Timer2/4/6Module_Constants
// ----------------------------------------------------------------------------
enum Timer2Module_Prescaler_Constants {
T2_PRATE_1_1 = 0b00,
T2_PRATE_1_4 = 0b01,
T2_PRATE_1_16 = 0b10,
T2_PRATE_1_64 = 0b11,
};
const struct Timer2Module_Prescaler Timer2Module_Prescaler = {
T2_PRATE_1_1,
T2_PRATE_1_4,
T2_PRATE_1_16,
T2_PRATE_1_64,
};
enum Timer2Module_Postscaler_Constants {
T2_RATE_1_1 = 0b0000,
T2_RATE_1_2 = 0b0001,
T2_RATE_1_3 = 0b0010,
T2_RATE_1_4 = 0b0011,
T2_RATE_1_5 = 0b0100,
T2_RATE_1_6 = 0b0101,
T2_RATE_1_7 = 0b0110,
T2_RATE_1_8 = 0b0111,
T2_RATE_1_9 = 0b1000,
T2_RATE_1_10 = 0b1001,
T2_RATE_1_11 = 0b1010,
T2_RATE_1_12 = 0b1011,
T2_RATE_1_13 = 0b1100,
T2_RATE_1_14 = 0b1101,
T2_RATE_1_15 = 0b1110,
T2_RATE_1_16 = 0b1111,
};
const struct Timer2Module_Postscaler Timer2Module_Postscaler = {
T2_RATE_1_1,
T2_RATE_1_2,
T2_RATE_1_3,
T2_RATE_1_4,
T2_RATE_1_5,
T2_RATE_1_6,
T2_RATE_1_7,
T2_RATE_1_8,
T2_RATE_1_9,
T2_RATE_1_10,
T2_RATE_1_11,
T2_RATE_1_12,
T2_RATE_1_13,
T2_RATE_1_14,
T2_RATE_1_15,
T2_RATE_1_16,
};
#endif
// ----------------------------------------------------------------------------
// Timer2/4/6Module
// ----------------------------------------------------------------------------
#if !defined(TIMER2_MODULE_DECLARED)
#define TIMER2_MODULE_DECLARED
#define TimerxModule_(name) Timer2Module_##name
#define TMRx TMR2
#define TMRxON T2CONbits.TMR2ON
#define TxCKPS T2CONbits.T2CKPS
#define TxOUTPS T2CONbits.T2OUTPS
#define PRx PR2
#elif !defined(TIMER4_MODULE_DECLARED)
#define TIMER4_MODULE_DECLARED
#define TimerxModule_(name) Timer4Module_##name
#define TMRx TMR4
#define TMRxON T4CONbits.TMR4ON
#define TxCKPS T4CONbits.T4CKPS
#define TxOUTPS T4CONbits.T4OUTPS
#define PRx PR4
#elif !defined(TIMER6_MODULE_DECLARED)
#define TIMER6_MODULE_DECLARED
#define TimerxModule_(name) Timer6Module_##name
#define TMRx TMR6
#define TMRxON T6CONbits.TMR6ON
#define TxCKPS T6CONbits.T6CKPS
#define TxOUTPS T6CONbits.T6OUTPS
#define PRx PR6
#define EXIT_LOOP
#endif
static int TimerxModule_(data);
static uint16_t TimerxModule_(getCount)() {
return TMRx;
}
static void TimerxModule_(setCount)(uint16_t count) {
TMRx = count;
}
static void TimerxModule_(start)() {
TMRxON = 1;
}
static void TimerxModule_(stop)() {
TMRxON = 0;
}
static const TimerModule TimerxModule_(instance) = {
TimerxModule_(getCount),
TimerxModule_(setCount),
TimerxModule_(start),
TimerxModule_(stop),
};
const TimerModule* TimerxModule_(constructor)(
char prescaler,
char postscaler,
uint8_t periodCount) {
TxCKPS = prescaler;
TxOUTPS = postscaler;
PRx = periodCount;
return &TimerxModule_(instance);
}
#undef TimerxModule_
#undef TMRx
#undef TMRxON
#undef TxCKPS
#undef TxOUTPS
#undef PRx
#ifndef EXIT_LOOP
#include "TimerModule.c"
#endif
|
k-ishigaki/Linesensor2017
|
src/hardware/Compare.h
|
<gh_stars>0
#ifndef COMPARE_H
#define COMPARE_H
#include <stdint.h>
/**
* Compare presetting count value with base timer count value.
*
* On compare matched, a event occur.
* The event may be user settable. (ex: software interrupt)
*/
struct Compare {
/**
* Set count value compared with base timer count.
*
* The count value range depend on that of base timer.
*/
void (*setComparedCount)(uint16_t);
};
#endif /* COMPARE_H */
|
k-ishigaki/Linesensor2017
|
src/application/DigitalPin.h
|
#ifndef DIGITAL_PIN_H
#define DIGITAL_PIN_H
#include <stdbool.h>
struct DigitalPin {
void (*setDirection)(bool);
bool (*read)(void);
void (*write)(bool);
};
#endif /* DIGITAL_PIN_H */
|
k-ishigaki/Linesensor2017
|
src/hardware/USART.h
|
<filename>src/hardware/USART.h
#ifndef USART_H
#define USART_H
#include <stdint.h>
struct USART {
/**
* Read from receive buffer.
*
* Before reading from the buffer, you must confirm that data exists
* in it.
*
* @return received data in receive buffer
*/
uint16_t (*read)(void);
/**
* Represent receive buffer status.
*
* If USART#read method can be used, this
* method returns true.
* To read from received buffer, see USART#read.
*
* @return true if received data exits<br>
* false if no data exits.
*/
bool (*hasReceived)(void);
/**
* Write to transmit buffer of the module.
*
* Before writing to the buffer, you must confirm that it is empty.
* {@code
* const USART* serial = Hardware.EUSART;
* ... (setup serial module)
* while(serial->isTransmitting);
* serial->write(data);
* }
*
* @param transmitting data to transmit buffer
*/
void (*write)(uint16_t);
/**
* Represent transmit buffer status.
*
* If USART#write method can be used, this
* method returns true.
* To write to transmit buffer, see USART#write.
*
* @return true if transmit buffer is full<br>
* false if it is empty
*/
bool (*isTransmitting)(void);
/**
* Reset reciver and re-enable it.
*
* When USART#getErrors != 0, clearing flag
* may be needed.
* Using this method, the errors can be cleared.
*/
void (*resetReceiver)(void);
/**
* Get errors in receiver.
*
* If you want to detect which errors occured, use
* USART_Error constants defined at Hardware.h.
* {@code
* const USART uasrt = Hardware.
* USART(...);
* uint8_t error = usart->getErrors();
* if(error & USART_Error.OVERRUN) {
* // overrun error occured
* } else if (error & USART_Error.FRAMING) {
* // framing error occured
* }
* }
*
* @return 0 if no error occurs<br>
* the kinds of error can be detect by<br>
* USART_Error
*/
uint8_t (*getErrors)(void);
};
#endif /* UNIVERSAL_RECEIVER_TRANSMITTER_H */
|
k-ishigaki/Linesensor2017
|
src/hardware/Capture.h
|
<filename>src/hardware/Capture.h
#ifndef CAPTURE_H
#define CAPTURE_H
#include <stdint.h>
/**
* Captures pin event and gets timer count value of that time.
*
* The got timer count is obtained at Capture#getCapturedCount.
*/
struct Capture {
/**
* Get the captured timer count value/
*
* If capture event occured when reading captured count,
* the value may be uncorrect.
*/
uint16_t (*getCapturedCount)(void);
};
#endif /* CAPTURE_H */
|
k-ishigaki/Linesensor2017
|
src/hardware/I2C.h
|
#ifndef I2C_H
#define I2C_H
#include <stdint.h>
#include <stdbool.h>
struct I2C {
/**
* Generate start consdition as a master.
*/
void (*generateStartCondition)(void);
/**
* Generate stop condition as a master.
*/
void (*generateStopCondition)(void);
/**
* Generate restart condition as a master.
*/
void (*generateRestartCondition)(void);
/**
* Check if I2C operation is pending.
*
* @return true if module is pending<br>
* false if not
*/
bool (*isPending)(void);
/**
* Write to buffer and start transmission.
*
* In master mode, this method is
*/
void (*startTransmission)(uint8_t);
/**
* Check if acknowledge existed at last transmission.
*
* @return true if acknowledge was received<br>
* false if not
*/
bool (*wasAcknowledged)(void);
/**
* Start reception.
*
* A acknowledge reservation must be determined so that
* the slave device can detect reception ending.
* The received value can be read I2CMaster#read method
* after reception sequence finished.
* {@code
* const struct I2CMaster* i2c = Hardware.I2CMaster(...);
* i2c->generateStartCondition();
* while (i2c->isPending());
* // send slave address and read bit
* i2c->startTransmission(ADDRESS << 1 | 0b00000001);
* while (i2c->isPending());
* // check slave acknowledge
* if (!(i2c->wasAcknowledged())) goto ERROR;
* // first byte reception
* i2c->startReception(true);
* while (i2c->isPending());
* uint8_t result1 = i2c->read();
* // second byte reception
* i2c->startReception(false);
* while (i2c->isPending());
* uint8_t result2 = i2c->read();
* i2c->generateStopCondition();
* while (i2c->isPending());
* }
*
* @param acknowledge reservation<br>
* acknowledge will be transmitted if true<br>
* not acknowledge will be transmitted if false
*/
void (*startReception)(bool);
/**
* Read from buffer.
*
* This method does not need waiting by I2CMaster#isPending method.
*
* @param buffer value
*/
uint8_t (*read)(void);
};
#endif /* I2C_H */
|
k-ishigaki/Linesensor2017
|
src/application/AnalogInputPin.c
|
#include "AnalogInputPin.h"
#include "IOPort.h"
#include "ADConverter.h"
#ifndef COMMON_DECLARATION
#define COMMON_DECLARATION
static void setPinModes_dummy(uint8_t pos, char mode) {
}
static uint8_t read_dummy(void) {
return 0;
}
static void write_dummy(uint8_t pos, uint8_t output) {
}
static void toggle_dummy(uint8_t pos) {
}
static const struct IOPort IOPort_dummy = {
setPinModes_dummy,
read_dummy,
write_dummy,
toggle_dummy,
};
static void selectInputChannel_dummy(char channel) {
}
static void startConversion_dummy(void) {
}
static bool isConverting_dummy(void) {
return false;
}
static uint16_t getResult_dummy(void) {
return 0;
}
static const struct ADConverter ADConverter_dummy = {
selectInputChannel_dummy,
startConversion_dummy,
isConverting_dummy,
getResult_dummy,
};
static const struct AnalogInputPin* AnalogInputPin0_constructor(const struct IOPort*, char, char, const struct ADConverter*, char);
static const struct AnalogInputPin* AnalogInputPin1_constructor(const struct IOPort*, char, char, const struct ADConverter*, char);
static const struct AnalogInputPin* AnalogInputPin2_constructor(const struct IOPort*, char, char, const struct ADConverter*, char);
static const struct AnalogInputPin* AnalogInputPin3_constructor(const struct IOPort*, char, char, const struct ADConverter*, char);
static const struct AnalogInputPin* (*AnalogInputPinn_constructor[4])(const struct IOPort*, char, char, const struct ADConverter*, char) = {
AnalogInputPin0_constructor,
AnalogInputPin1_constructor,
AnalogInputPin2_constructor,
AnalogInputPin3_constructor,
};
const struct AnalogInputPin* createAnalogInputPin(
const struct IOPort* port,
char position,
char analogInputPinMode,
const struct ADConverter* adc,
char inputChannel) {
static char index = 0;
return AnalogInputPinn_constructor[index++](
port,
position,
analogInputPinMode,
adc,
inputChannel);
}
#endif /* COMMON_DECLARATION */
#if !defined(ANALOG_INPUT_PIN0_DECLARED)
#define ANALOG_INPUT_PIN0_DECLARED
#define this_(name) AnalogInputPin0_##name
#elif !defined(ANALOG_INPUT_PIN1_DECLARED)
#define ANALOG_INPUT_PIN1_DECLARED
#define this_(name) AnalogInputPin1_##name
#elif !defined(ANALOG_INPUT_PIN2_DECLARED)
#define ANALOG_INPUT_PIN2_DECLARED
#define this_(name) AnalogInputPin2_##name
#elif !defined(ANALOG_INPUT_PIN3_DECLARED)
#define ANALOG_INPUT_PIN3_DECLARED
#define this_(name) AnalogInputPin3_##name
#define EXIT_LOOP
#endif
static const struct ADConverter* this_(adc) = &ADConverter_dummy;
static char this_(inputChannel);
static int this_(read)() {
this_(adc)->selectInputChannel(this_(inputChannel));
this_(adc)->startConversion();
while (this_(adc)->isConverting());
return this_(adc)->getResult();
}
static const struct AnalogInputPin this_(instance) = {
this_(read),
};
static const struct AnalogInputPin* this_(constructor)(
const struct IOPort* port,
char position,
char analogInputPinMode,
const struct ADConverter* adc,
char inputChannel) {
port->setPinModes(position, analogInputPinMode);
port = &IOPort_dummy;
this_(adc) = adc;
this_(inputChannel) = inputChannel;
return &this_(instance);
}
#undef this_
#if !defined(EXIT_LOOP)
#include "AnalogInputPin.c"
#endif
|
k-ishigaki/Linesensor2017
|
src/hardware/ADConverter.h
|
<filename>src/hardware/ADConverter.h
#ifndef AD_CONVERTER_H
#define AD_CONVERTER_H
#include <stdbool.h>
#include <stdint.h>
/**
* Analog to Digital Converter.
*/
struct ADConverter {
/**
* Select input channel of the AD conveter.
*
* Please ensure the pin is analog inputable before connect
* ad conveter input channel to it.
* AD conveter often needs acquisition time, so you should make time
* before call {@code ADConverter#startConversion} when input
* channel is changed.
* The channel identifier is defined at Hardware.h
*
* @param input channel identifier
*/
void (*selectInputChannel)(char);
/**
* Initiate AD conversion cycle.
*
* The AD conversion is started if previous conversion is ended.
* If previous one continues, wait for it is finished. So, please
* note that this method may take time.
*
* Before start conversion, {@code ADConverter#eneble} and
* (if needed) {@code ADConverter#selectInputChannel} should
* be called.
*
* If interrupt is enabled by ADConverterInterruptService,
* the registered listener is called at finish of the convertion.
*/
void (*startConversion)(void);
/**
* Return whether AD conversion continues or not.
*
* If you don't use interrupt of AD converter module, it is recommended
* using this method after ADConverter#startConversion.
*
* example:
* {@code
* adc->startConversion();
* while(adc->isConverting()); // wait for finishing conversion
* int result = adc->getResult();
* }
*
* @return true if AD conversion continues, false if not
*/
bool (*isConverting)(void);
/**
* Get result value of previous AD conversion.
*
* The resolution of AD conversion can be obtained from
* ADConverter#getResolution.
*
* @return result value of previous AD conversion
*/
uint16_t (*getResult)(void);
};
#endif /* AD_CONVERTER_H */
|
k-ishigaki/Linesensor2017
|
src/hardware/NativeInterrupts.h
|
#ifndef NATIVE_INTERRUPTS_H
#define NATIVE_INTERRUPTS_H
/**
* A interface of interrupt listener.
*
* When using native interrupt of peripherals, only you have to do is
* create this instance and register it to interrupt service that you
* want to listen.
* example:
* {@code
* // creating instance of interrupt listener
* static void onInterrupt() {
* // do something when interrupt
* }
* static InterruptListener listener = {
* onInterrupt,
* };
* ...
* const InterruptService* intService;
* ...
* intService = Hardware.SomeInterruptService(...);
* ...
* // register listener to service
* intService->registerListener(&listener);
* intService->enableInterrupt();
* // when interrupt occured, onInterrupt method is called
* }
*/
struct InterruptListener {
/**
* Called on a interrupt occured if registerd by the service.
*
* This method must be terminated shortly (about within 10 us)
* because it is called at interrupt vector and
* other any interrupts cannnot occur.
*/
void (*onInterrupt)(void);
};
/*+
* A interface of interrupt vector and interrupt service.
*
* Other modules can use the interrupt through
* {@code
* intService->registerListener(listener);
* intService->enableInterrupt();
* }
* where the argument are explained below.
*/
struct InterruptService {
/**
* Add a listener handles interrupt.
*
* If you call this method twice, only one listener is registered.
* (First registerd listener is overwriten by second one.)
* This method may takes time to register listener to interrupt
* vector, so it is recommended calling it at initilization.
*
* @param interrupt listener
*/
void (*registerListener)(const struct InterruptListener*);
/**
* Enable the interrupt.
*
* This method must be called after calling
* InterruptService#registerListener.
*/
void (*enableInterrupt)(void);
/**
* Disable the interrupt.
*
* You should call this method when stop the interrupt
* because it is unable to remove registerd listener.
*/
void (*disableInterrupt)(void);
};
#endif /* NATIVE_INTERRUPTS_H */
|
k-ishigaki/Linesensor2017
|
src/application/Application.h
|
<filename>src/application/Application.h
#ifndef APPLICATION_H
#define APPLICATION_H
/**
* Initialize almost all instances and ready for application.
*
* This method is called by main method.
*/
void initilize(void);
/**
* This method called by main loop when any other interrupts or tasks running.
*/
void idle(void);
#endif /* APPLICATION_H */
|
k-ishigaki/Linesensor2017
|
src/hardware/TimerModule.h
|
<reponame>k-ishigaki/Linesensor2017
#ifndef TIMER_MODULE_H
#define TIMER_MODULE_H
#include <stdint.h>
#include <stdbool.h>
/**
* Timer module interface.
* If you want to use timer overflow interrupt, use InterruptService
* interface.
*/
typedef struct {
/**
* Get counter value of timer module.
*
* At several device, countup operation is stoped temporarily to
* set accurate counter value.
* So you should pay attention to the temporary timer stop.
*
* @return counter value of timer module<br>
* (8bit timer) 0~255<br>
* (16bit timer) 0~65535
*/
uint16_t (*getCount)(void);
/**
* Set counter value of timer module.
*
* At several device, countup operation is stoped temporarily to
* get accurate counter value.
* So you should pay attention to the temporary timer stop.
*
* @param counter value of timer module<br>
* (8bit timer) 0~255<br>
* (16bit timer) 0~65535
*/
void (*setCount)(uint16_t);
/**
* Start Counting.
*
* When timer module constructor called, the counting is disabled.
* So this method is needed to start timer operation.
* But timer counting is always enabled at timer module which counting
* cannot be stoped. (see datasheet)
*/
void (*start)(void);
/**
* Stop Counting.
*
* If you stop timer counting operation temporarily, use this method.
* TimerModule#start method can be used for resumption operation.
* But timer counting is always enabled at timer module which counting
* cannot be stoped. (see datasheet)
*/
void (*stop)(void);
} TimerModule;
/**
* Timer gate control interface.
*/
typedef struct {
/**
* Get current state of gate value.
*
* @return true if high-level, false if low-level
*/
bool (*getState)(void);
/**
* Start single pulse aquisition.
*
* This method can be used when gate control mode is SINGLE_PULSE.
* If interrupt is enabled at
* TimerGateControlInterruptService#enableInterrupt, a interrupt
* occur at the end of aquisition.
* If you don't use interrupt, TimerGateControl#isWaitingSinglePulse
* is can be used for aquisition of a single pulse.
*
* example:
* {@code
* // timer module setup
* const TimerModule* tm = Hardware.Timer1Module;
* tm->enable();
* tm->selectClockSource(Timer1Module_ClockSource.XXX);
* tm->selectPrescaler(Timer1Module_Prescaler.XXX);
* tm->setMode(Timer1Module_Mode.COUNTER);
* tm->stop();
* tm->setCount(0);
* // timer gate control setup
* const TimerGateControl* tgc = tm->Timer1GateControl;
* tgc->selectSource(Timer1GateControl_Source.XXX);
* tgc->selectMode(Timer1GateControl_Mode.SINGLE_PULSE);
* // do single pulse aquisition and get result value
* tm->start();
* tgc->startSinglePulseAquisition();
* while(tgc->isWaitingSinglePulse());
* uint16_t result = tm->getCount();
* }
*/
void (*startSinglePulseAquisition)(void);
/**
* Represent single pulse aquisition state.
*
* @return true if waiting single pulse edge<br>
* false if aquisition is completed or not conducted.
*/
bool (*isWaitingSinglePulse)(void);
} TimerGateControl;
#endif /* TIMER_MODULE_H */
|
k-ishigaki/Linesensor2017
|
src/application/LED.h
|
#ifndef LED_H
#define LED_H
struct LED {
void (*turnOn)(void);
void (*turnOff)(void);
};
#endif /* LED_H */
|
k-ishigaki/Linesensor2017
|
src/application/LineSensor.c
|
<reponame>k-ishigaki/Linesensor2017
#include "LineSensor.h"
#include <stddef.h>
#include "LED.h"
#include "PhotoTransistor.h"
#include "DigitalPin.h"
#include "AnalogInputPin.h"
#include "Hardware.h"
#ifndef COMMON_DECLARATION
#define COMMON_DECLARATION
// declared at DigitalPin.c
extern const struct DigitalPin* createDigitalPin(const struct IOPort*, char, char, char);
// declared at LED.c
extern const struct LED* createLED(const struct DigitalPin*);
// declared at AnalogInputPin.c
extern const struct AnalogInputPin* createAnalogInputPin(const struct IOPort*, char, char, const struct ADConverter*, char);
// declared at PhotoTransistor.c
extern const struct PhotoTransistor* createPhotoTransistor(const struct AnalogInputPin*);
static const struct LED* LED0_getter() {
static const struct LED* instance = NULL;
if (instance == NULL) {
instance = createLED(createDigitalPin(
Hardware.PortC(),
1 << 2,
IOPort_PinMode.DIGITAL_INPUT,
IOPort_PinMode.DIGITAL_OUTPUT));
}
return instance;
}
static const struct LED* LED1_getter() {
static const struct LED* instance = NULL;
if (instance == NULL) {
instance = createLED(createDigitalPin(
Hardware.PortC(),
1 << 3,
IOPort_PinMode.DIGITAL_INPUT,
IOPort_PinMode.DIGITAL_OUTPUT));
}
return instance;
}
static const struct LED* LED2_getter() {
static const struct LED* instance = NULL;
if (instance == NULL) {
instance = createLED(createDigitalPin(
Hardware.PortC(),
1 << 4,
IOPort_PinMode.DIGITAL_INPUT,
IOPort_PinMode.DIGITAL_OUTPUT));
}
return instance;
}
static const struct LED* LED3_getter() {
static const struct LED* instance = NULL;
if (instance == NULL) {
instance = createLED(createDigitalPin(
Hardware.PortC(),
1 << 5,
IOPort_PinMode.DIGITAL_INPUT,
IOPort_PinMode.DIGITAL_OUTPUT));
}
return instance;
}
static const struct ADConverter* getADConverterModule() {
static const struct ADConverter* instance = NULL;
if (instance == NULL) {
instance = Hardware.ADConverterModule(
ADConverterModule_PositiveReference.VDD,
ADConverterModule_NegativeReference.VSS,
ADConverterModule_ConversionClock.F_OSC_DIV_32);
}
return instance;
}
static const struct PhotoTransistor* PhotoTransistor0_getter() {
static const struct PhotoTransistor* instance = NULL;
if (instance == NULL) {
instance = createPhotoTransistor(createAnalogInputPin(
Hardware.PortA(),
1 << 0,
IOPort_PinMode.ANALOG_INPUT,
getADConverterModule(),
ADConverterModule_InputChannel.AN0));
}
return instance;
}
static const struct PhotoTransistor* PhotoTransistor1_getter() {
static const struct PhotoTransistor* instance = NULL;
if (instance == NULL) {
instance = createPhotoTransistor(createAnalogInputPin(
Hardware.PortA(),
1 << 1,
IOPort_PinMode.ANALOG_INPUT,
getADConverterModule(),
ADConverterModule_InputChannel.AN1));
}
return instance;
}
static const struct PhotoTransistor* PhotoTransistor2_getter() {
static const struct PhotoTransistor* instance = NULL;
if (instance == NULL) {
instance = createPhotoTransistor(createAnalogInputPin(
Hardware.PortA(),
1 << 2,
IOPort_PinMode.ANALOG_INPUT,
getADConverterModule(),
ADConverterModule_InputChannel.AN2));
}
return instance;
}
static const struct PhotoTransistor* PhotoTransistor3_getter() {
static const struct PhotoTransistor* instance = NULL;
if (instance == NULL) {
instance = createPhotoTransistor(createAnalogInputPin(
Hardware.PortA(),
1 << 4,
IOPort_PinMode.ANALOG_INPUT,
getADConverterModule(),
ADConverterModule_InputChannel.AN3));
}
return instance;
}
const struct LineSensor LineSensor = {
LED0_getter,
PhotoTransistor0_getter,
LED1_getter,
PhotoTransistor1_getter,
LED2_getter,
PhotoTransistor2_getter,
LED3_getter,
PhotoTransistor3_getter,
};
#endif /* COMMON_DECLARATION */
|
k-ishigaki/Linesensor2017
|
src/hardware/PWM.h
|
#ifndef PWM_H
#define PWM_H
#include <stdint.h>
/**
* Configurator of PWM output.
*/
struct PWM {
/**
* Set duty cycle count.
*
* @param duty cycle count
*/
void (*setDutyCycle)(uint16_t);
};
#endif /* PWM_H */
|
k-ishigaki/Linesensor2017
|
src/hardware/InterruptOnChange.h
|
#ifndef INTERRUPT_ON_CHANGE_H
#define INTERRUPT_ON_CHANGE_H
#include <stdint.h>
#include <stdbool.h>
typedef struct {
uint8_t positions;
uint8_t status;
} InterruptOnChange_ChangedPins;
typedef struct {
/**
* Get pin positions which state have been changed.
*
* The detection of pin state change is conducted after previous
* end of interrupt on change (IOC) interrupt or resets.
* This method must be called while IOC interrupt so that a you can
* detect changed pin positions (and some device must clear interrupt
* flags in it).
*
* You cannnot obtain changed pin status (ex rising edge or falling
* edge). If you want to obtain these, use IOPort#read 'before' calling
* this method. But the results of these are not under warranty.
* (The correctness depends on device hardware structure.)
*
* A return value represented by bit string. example:
* {@code
* uint8_t pos = ioc->getChangedPinPositions();
* if(pos & 0b00000001) {
* // bit 0 is changed
* }
* if(pos & 0b00011000) {
* // bit 3 and 4 are changed
* }
* }
*
* @return changed pin positions and status
*/
InterruptOnChange_ChangedPins* (*getChangedPins)();
} InterruptOnChange;
#endif /* INTERRUPT_ON_CHANGE_H */
|
k-ishigaki/Linesensor2017
|
src/hardware/AlternatePinFunction.c
|
#include <xc.h>
#include "Hardware.h"
#define AlternatePinFunction_(name) AlternatePinFunction_##name
enum AlternatePinFunction_(RXAndDT_Constant) {
RX_DT_RC5 = 0,
RX_DT_RA1 = 1,
};
const struct AlternatePinFunction_(RXAndDT) AlternatePinFunction_(RXAndDT) = {
RX_DT_RC5,
RX_DT_RA1,
};
enum AlternatePinFunction_(SDO_Constant) {
SDO_RC2 = 0,
SDO_RA4 = 1,
};
const struct AlternatePinFunction_(SDO) AlternatePinFunction_(SDO) = {
SDO_RC2,
SDO_RA4,
};
enum AlternatePinFunction_(SS_Constant) {
SS_RC3 = 0,
SS_RA3 = 1,
};
const struct AlternatePinFunction_(SS) AlternatePinFunction_(SS) = {
SS_RC3,
SS_RA3,
};
enum AlternatePinFunction_(T1G_Constant) {
T1G_RA4 = 0,
T1G_RA3 = 1,
};
const struct AlternatePinFunction_(T1G) AlternatePinFunction_(T1G) = {
T1G_RA4,
T1G_RA3,
};
enum AlternatePinFunction_(TXAndCK_Constant) {
TX_CK_RC4 = 0,
TX_CK_RA0 = 1,
};
const struct AlternatePinFunction_(TXAndCK) AlternatePinFunction_(TXAndCK) = {
TX_CK_RC4,
TX_CK_RA0,
};
enum AlternatePinFunction_(P1D_Constant) {
P1D_RC2 = 0,
P1D_RC0 = 1,
};
const struct AlternatePinFunction_(P1D) AlternatePinFunction_(P1D) = {
P1D_RC2,
P1D_RC0,
};
enum AlternatePinFunction_(P1C_Constant) {
P1C_RC3 = 0,
P1C_RC1 = 1,
};
const struct AlternatePinFunction_(P1C) AlternatePinFunction_(P1C) = {
P1C_RC3,
P1C_RC1,
};
enum AlternatePinFunction_(P2B_Constant) {
P2B_RC2 = 0,
P2B_RA4 = 1,
};
const struct AlternatePinFunction_(P2B) AlternatePinFunction_(P2B) = {
P2B_RC2,
P2B_RA4,
};
enum AlternatePinFunction_(CCP2_Constant) {
CCP2_RC3 = 0,
CCP2_RA5 = 1,
};
const struct AlternatePinFunction_(CCP2) AlternatePinFunction_(CCP2) = {
CCP2_RC3,
CCP2_RA5,
};
void AlternatePinFunction_(configure)(
char RXAndDT,
char SDO,
char SS,
char T1G,
char TXAndCK,
char P1D,
char P1C,
char P2B,
char CCP2) {
APFCON0bits.RXDTSEL = RXAndDT;
APFCON0bits.SDOSEL = SDO;
APFCON0bits.SSSEL = SS;
APFCON0bits.T1GSEL = T1G;
APFCON0bits.TXCKSEL = TXAndCK;
APFCON1bits.P1DSEL = P1D;
APFCON1bits.P1CSEL = P1C;
APFCON1bits.P2BSEL = P2B;
APFCON1bits.CCP2SEL = CCP2;
}
|
k-ishigaki/Linesensor2017
|
src/hardware/IOPort.c
|
#include <xc.h>
#include "Hardware.h"
#ifndef IO_PORT_COMMON_DECRARED
#define IO_PORT_COMMON_DECRARED
// ----------------------------------------------------------------------------
// IOPort_PinMode
// ----------------------------------------------------------------------------
enum IOPort_PinMode_Constants {
DIGITAL_INPUT,
DIGITAL_INPUT_WITH_INTERNAL_PULLUP,
DIGITAL_OUTPUT,
ANALOG_INPUT,
};
const struct IOPort_PinMode IOPort_PinMode = {
DIGITAL_INPUT,
DIGITAL_INPUT_WITH_INTERNAL_PULLUP,
DIGITAL_OUTPUT,
ANALOG_INPUT,
};
#endif
// ----------------------------------------------------------------------------
// Port A, Port C
// ----------------------------------------------------------------------------
#if !defined(PORTA_DECLARED)
#define PORTA_DECLARED
#define Portx_(name) PortA_##name
#define PORTx PORTA
#define ANSELx ANSELA
#define TRISx TRISA
#define LATx LATA
#define WPUx WPUA
#elif !defined(PORTC_DECLARED)
#define PORTC_DECLARED
#define Portx_(name) PortC_##name
#define PORTx PORTC
#define ANSELx ANSELC
#define TRISx TRISC
#define LATx LATC
#define WPUx WPUC
#define EXIT_LOOP
#endif
static void Portx_(setPinModes)(uint8_t bits, char mode) {
switch((enum IOPort_PinMode_Constants)mode) {
case DIGITAL_INPUT:
#ifdef ANSELx
ANSELx &= ~bits;
#endif
#ifdef WPUx
WPUx &= ~bits;
#endif
TRISx |= bits;
break;
case DIGITAL_INPUT_WITH_INTERNAL_PULLUP:
#ifdef ANSELx
ANSELx &= ~bits;
#endif
#ifdef WPUx
OPTION_REGbits.nWPUEN = 0;
WPUx |= bits;
#endif
TRISx |= bits;
break;
case DIGITAL_OUTPUT:
#ifdef ANSELx
ANSELx &= ~bits;
#endif
TRISx &= ~bits;
break;
case ANALOG_INPUT:
#ifdef ANSELx
ANSELx |= bits;
TRISx |= bits;
#endif
break;
}
}
static uint8_t Portx_(read)() {
return PORTx;
}
static void Portx_(write)(uint8_t pos, uint8_t bits) {
LATx = LATx | (pos & bits);
LATx = LATx & (~pos | bits);
}
static void Portx_(toggle)(uint8_t pos) {
uint8_t bits = ~LATx;
LATx = LATx | (pos & bits);
LATx = LATx & (~pos | bits);
}
static const struct IOPort Portx_(instance) = {
Portx_(setPinModes),
Portx_(read),
Portx_(write),
Portx_(toggle),
};
const struct IOPort* Portx_(constructor)() {
return &Portx_(instance);
}
#undef Portx_
#undef PORTx
#undef ANSELx
#undef TRISx
#undef LATx
#undef WPUx
#if !defined(EXIT_LOOP)
#include "IOPort.c"
#endif
|
k-ishigaki/Linesensor2017
|
src/hardware/FixedVoltageReference.c
|
#include <xc.h>
#include "Hardware.h"
// ----------------------------------------------------------------------------
// FixedVoltageReference_Constants
// ----------------------------------------------------------------------------
enum FixedVoltageReference_Buffer1Reference_Constants {
B1_OFF = 0b00,
B1_OUTPUT_1x = 0b01,
B1_OUTPUT_2x = 0b10,
B1_OUTPUT_4x = 0b11,
};
const struct FixedVoltageReference_Buffer1Reference FixedVoltageReference_Buffer1Reference = {
B1_OFF,
B1_OUTPUT_1x,
B1_OUTPUT_2x,
B1_OUTPUT_4x,
};
enum FixedVoltageReference_Buffer2Reference_Constants {
B2_OFF = 0b00,
B2_OUTPUT_1x = 0b01,
B2_OUTPUT_2x = 0b10,
B2_OUTPUT_4x = 0b11,
};
const struct FixedVoltageReference_Buffer2Reference FixedVoltageReference_Buffer2Reference = {
B2_OFF,
B2_OUTPUT_1x,
B2_OUTPUT_2x,
B2_OUTPUT_4x,
};
// ----------------------------------------------------------------------------
// FixedVoltageReference
// ----------------------------------------------------------------------------
#define FixedVoltageReference_(name) FixedVoltageReference_##name
void FixedVoltageReference_(configure)(
char buffer1Output,
char buffer2Output) {
FVRCONbits.ADFVR = buffer1Output;
FVRCONbits.CDAFVR = buffer2Output;
while(!FVRCONbits.FVRRDY);
}
|
k-ishigaki/Linesensor2017
|
src/hardware/IOPort.h
|
#ifndef IO_PORT_H
#define IO_PORT_H
#include <stdint.h>
/**
* Defines IO port characteristics includes port configs.
*
* A function of ADC is not included because ADC module is not part of
* IO port module.
*
* usage: write to output latch
* {@code
* const struct IOPort* port = Hardware.PortA; // get instance of Port A
* // set all pins to digital output
* port->setPinModes(0xFF, IOPort_PinMode.DIGITAL_OUTPUT);
* port->writeDigital(0x55); // pin 0, 2, 4, 6: output high
* // pin 1, 3, 5, 7: output low
* }
*
* usage: read port status
* {@code
* const struct IOPort* port = Hardware.PortA;
* // set all pins to digital input
* port->setPinModes(0xFF, IOPort_PinMode.DIGITAL_INPUT);
* uint8_t result = port->readDigital(); // read port and store
* }
*/
struct IOPort {
/**
* Apply pin mode to selected pins.
*
* You can select pins at first argument, and pin mode at second
* argument.
* The pin mode is defined at Hardware.h.
* Please check data sheet not to select unsupported pins.
*
* For example:
* {@code
* // set pin 0 and pin 4 to digital input
* port->setPinModes(0b00010001, IOPort_PinMode.DIGITAL_INPUT);
* }
*
* @param pin positions
* @param pin mode
*/
void (*setPinModes)(uint8_t, char);
/**
* Read levels on the digital input pins.
*
* If a pin is not digital input, the return value is not specified.
*
* @return 1 if high level , else 0 for respective pins
*/
uint8_t (*read)(void);
/**
* Write outputs to digital output pins.
*
* If a pin is not digital output or not selected by first argument,
* its state is unchanged.
*
* @param pin positions
* @param a output levels for respective pins<br>
* 1 = output high<br>
* 0 = output low
*/
void (*write)(uint8_t, uint8_t);
/**
* Toggle outputs of digital output pins.
*
* If a pin is not digital output of not selected by first arguments,
* its status is unchanged.
*
* @param pin positions
*/
void (*toggle)(uint8_t);
};
#endif /* IO_PORT_H */
|
k-ishigaki/Linesensor2017
|
src/hardware/Hardware.h
|
<filename>src/hardware/Hardware.h
/*
* Hardware.h
* definitions for PIC16F1825
*/
#ifndef HARDWARE_H
#define HARDWARE_H
// ----------------------------------------------------------------------------
// device configurations
// ----------------------------------------------------------------------------
// CLKOUT function is disabled. I/O or oscillator function on the CLKOUT pin
#pragma config CLKOUTEN = OFF
// WDT disabled
#pragma config WDTE = OFF
// PWRT disabled
#pragma config PWRTE = OFF
// Program memory code protection is disabled
#pragma config CP = OFF
// Brown-out Reset disabled
#pragma config BOREN = OFF
// Fail-Safe Clock Monitor is disabled
#pragma config FCMEN = OFF
// MCLR/VPP pin function is MCLR
#pragma config MCLRE = ON
// Data memory code protection is disabled
#pragma config CPD = OFF
// Internal/External Switchover mode is disabled
#pragma config IESO = OFF
// INTOSC oscillator: I/O function on CLKIN pin
#pragma config FOSC = INTOSC
// Stack Overflow or Underflow will cause a Reset
#pragma config STVREN = ON
// Brown-out Reset Voltage (Vbor), low trip point selected.
#pragma config BORV = LO
// Low-voltage programming enabled
#pragma config LVP = ON
// Write protection off
#pragma config WRT = OFF
// 4x PLL enabled
#pragma config PLLEN = ON
// ----------------------------------------------------------------------------
// constants
// ----------------------------------------------------------------------------
#define OPERATING_VOLTAGE 5.0
#define OPERATING_FREQUENCY 32000000L
// ----------------------------------------------------------------------------
// NativeInterrupts
// ----------------------------------------------------------------------------
#include "NativeInterrupts.h"
// ----------------------------------------------------------------------------
// AlternatePinFunction
// ----------------------------------------------------------------------------
struct AlternatePinFunction_RXAndDT {
char RC5;
char RA1;
};
extern const struct AlternatePinFunction_RXAndDT AlternatePinFunction_RXAndDT;
struct AlternatePinFunction_SDO {
char RC2;
char RA4;
};
extern const struct AlternatePinFunction_SDO AlternatePinFunction_SDO;
struct AlternatePinFunction_SS {
char RC3;
char RA3;
};
extern const struct AlternatePinFunction_SS AlternatePinFunction_SS;
struct AlternatePinFunction_T1G {
char RA4;
char RA3;
};
extern const struct AlternatePinFunction_T1G AlternatePinFunction_T1G;
struct AlternatePinFunction_TXAndCK {
char RC4;
char RA0;
};
extern const struct AlternatePinFunction_TXAndCK AlternatePinFunction_TXAndCK;
struct AlternatePinFunction_P1D {
char RC2;
char RC0;
};
extern const struct AlternatePinFunction_P1D AlternatePinFunction_P1D;
struct AlternatePinFunction_P1C {
char RC3;
char RC1;
};
extern const struct AlternatePinFunction_P1C AlternatePinFunction_P1C;
struct AlternatePinFunction_P2B {
char RC2;
char RA4;
};
extern const struct AlternatePinFunction_P2B AlternatePinFunction_P2B;
struct AlternatePinFunction_CCP2 {
char RC3;
char RA5;
};
extern const struct AlternatePinFunction_CCP2 AlternatePinFunction_CCP2;
// ----------------------------------------------------------------------------
// OscillatorModule
// ----------------------------------------------------------------------------
struct OscillatorModule_InternalClockFrequency {
char HF_16MHz;
char HF_8MHz;
char HF_4MHz;
char HF_2MHz;
char HF_1MHz;
char HF_500kHz;
char HF_250kHz;
char HF_125kHz;
char MF_500kHz;
char MF_250kHz;
char MF_125kHz;
char MF_62500Hz;
char HF_31250Hz;
char MF_31250Hz;
char LF_31kHz;
};
extern const struct OscillatorModule_InternalClockFrequency OscillatorModule_InternalClockFrequency;
struct OscillatorModule_PhaseLockedLoop {
char ENABLE;
char DISABLE;
};
extern const struct OscillatorModule_PhaseLockedLoop OscillatorModule_PhaseLockedLoop;
struct OscillatorModule_SystemClockSource {
/** Internal oscillator block */
char INTERNAL;
/** Secondary (SOSC) oscillator */
char SECONDARY;
/** Primary clock (determined by FOSC<3:0> in CONFIG1H) */
char DETERMINED_BY_CONFIG;
};
extern const struct OscillatorModule_SystemClockSource OscillatorModule_SystemClockSource;
// ----------------------------------------------------------------------------
// IOPort
// ----------------------------------------------------------------------------
#include "IOPort.h"
struct IOPort_PinMode {
char DIGITAL_INPUT;
char DIGITAL_INPUT_WITH_INTERNAL_PULLUP;
char DIGITAL_OUTPUT;
char ANALOG_INPUT;
};
/** defined at IOPort.c */
extern const struct IOPort_PinMode IOPort_PinMode;
// ----------------------------------------------------------------------------
// ADConverterModule
// ----------------------------------------------------------------------------
#include "ADConverter.h"
struct ADConverterModule_PositiveReference {
char FVR;
char VREF_PLUS;
char VDD;
};
extern const struct ADConverterModule_PositiveReference ADConverterModule_PositiveReference;
struct ADConverterModule_NegativeReference {
char VREF_MINUS;
char VSS;
};
extern const struct ADConverterModule_NegativeReference ADConverterModule_NegativeReference;
struct ADConverterModule_ConversionClock {
char F_RC;
char F_OSC_DIV_64;
char F_OSC_DIV_32;
char F_OSC_DIV_16;
char F_OSC_DIV_8;
char F_OSC_DIV_4;
char F_OSC_DIV_2;
};
extern const struct ADConverterModule_ConversionClock ADConverterModule_ConversionClock;
struct ADConverterModule_InputChannel {
char FVR_BUFFER_1;
char DAC;
char TEMPERATURE_INDICATOR;
char AN7;
char AN6;
char AN5;
char AN4;
char AN3;
char AN2;
char AN1;
char AN0;
};
extern const struct ADConverterModule_InputChannel ADConverterModule_InputChannel;
// ----------------------------------------------------------------------------
// TimerModule
// ----------------------------------------------------------------------------
#include "TimerModule.h"
struct Timer0Module_ClockSource {
/** external T0CKI pin */
char T0CKI;
/** capacitive sensing oscillator */
char CPSCLK;
/** internal instruction cycle clock */
char F_OSC_DIV_4;
};
extern const struct Timer0Module_ClockSource Timer0Module_ClockSource;
struct Timer0Module_Prescaler {
char RATE_1_1;
char RATE_1_2;
char RATE_1_4;
char RATE_1_8;
char RATE_1_16;
char RATE_1_32;
char RATE_1_64;
char RATE_1_128;
char RATE_1_256;
};
extern const struct Timer0Module_Prescaler Timer0Module_Prescaler;
// timer0 module postscaler is not selectable
struct Timer1Module_ClockSource {
/**
* delicated low-power 32.768kHz oscillator circuit
* between pins T1OSI and T1OSO
*/
char T1OSC_SYNC;
/**
* delicated low-power 32.768kHz oscillator circuit
* (not sync with Fosc)
* between pins T1OSI and T1OSO
*/
char T1OSC_NOT_SYNC;
/** capacitive sensing oscillator */
char CPSCLK_SYNC;
/** capacitive sensing oscillator (not sync with Fosc) */
char CPSCLK_NOT_SYNC;
/** external clock on T1CKI pin */
char T1CKI_SYNC;
/** external clock on T1CKI pin (not sync with Fosc) */
char T1CKI_NOT_SYNC;
/** system clock */
char F_OSC;
/** internal instruction cycle clock */
char F_OSC_DIV_4;
};
extern const struct Timer1Module_ClockSource Timer1Module_ClockSource;
struct Timer1Module_Prescaler {
char RATE_1_1;
char RATE_1_2;
char RATE_1_4;
char RATE_1_8;
};
extern const struct Timer1Module_Prescaler Timer1Module_Prescaler;
struct Timer1GateControl_Source {
/** timer1 gate pin */
char T1G;
/** overflow of timer0 */
char TIMER0_OVERFLOW;
/** comparator1 output */
char SYNC_C1OUT;
/** comparator2 output */
char SYNC_C2OUT;
};
extern const struct Timer1_GateControlSource Timer1_GateControlSource;
struct Timer1GateControl_Mode {
char ENABLE_POSITIVE;
char ENABLE_NEGATIVE;
char TOGGLE_POSITIVE;
char TOGGLE_NEGATIVE;
char SINGLE_PULSE_POSITIVE;
char SINGLE_PULSE_NEGATIVE;
char TOGGLE_AND_SINGLE_PULSE_POSITIVE;
char TOGGLE_AND_SINGLE_PULSE_NEGATIVE;
};
extern const struct Timer1GateControl_Mode Timer1GateControl_Mode;
// timer2/4/6 module have only one clock source (Fosc/4)
struct Timer2Module_Prescaler {
char RATE_1_1;
char RATE_1_4;
char RATE_1_16;
char RATE_1_64;
};
extern const struct Timer2Module_Prescaler Timer2Module_Prescaler;
struct Timer2Module_Postscaler {
char RATE_1_1;
char RATE_1_2;
char RATE_1_3;
char RATE_1_4;
char RATE_1_5;
char RATE_1_6;
char RATE_1_7;
char RATE_1_8;
char RATE_1_9;
char RATE_1_10;
char RATE_1_11;
char RATE_1_12;
char RATE_1_13;
char RATE_1_14;
char RATE_1_15;
char RATE_1_16;
};
extern const struct Timer2Module_Postscaler Timer2Module_Postscaler;
// ----------------------------------------------------------------------------
// CCPModule
// ----------------------------------------------------------------------------
#include "Capture.h"
#include "Compare.h"
#include "PWM.h"
struct CaptureModule_Mode {
char EVERY_FALLING_EDGE;
char EVERY_RISING_EDGE;
char EVERY_4TH_RISING_EDGE;
char EVERY_16TH_RISING_EDGE;
};
extern const struct CaptureModule_Mode CaptureModule_Mode;
struct CompareModule_Mode {
/**
* initialize ECCPx pin low
*
* set output on compare match (set CCPxIF)
*/
char LOW_TO_HIGH;
/**
* initialize ECCPx pin high
*
* clear output on compare match (set CCPxIF)
*/
char HIGH_TO_LOW;
/**
* generate software interrupt only
*
* ECCPx pin reverts to I/O state
*/
char SOFTWARE_INTERRUPT;
/**
* Special Event Trigger(not implemented on CCP4 and CCP5)
*
* (ECCPx resets Timer, sets CCPxIF bit starts A/D conversion if A/D
* module is enabled)
*/
char SPECIAL_EVENT_TRIGGER;
};
extern const struct CompareModule_Mode CompareModule_Mode;
struct PWMModule_BaseTimer {
char TIMER2;
char TIMER4;
char TIMER6;
};
extern const struct PWMModule_BaseTimer PWMModule_BaseTimer;
struct PWMModule_OutputConfig {
char SINGLE;
char FULL_BRIDGE_FORWARD;
char HALF_BRIDGE;
char FULL_BRIDGE_REVERCE;
};
extern const struct PWMModule_OutputConfig PWMModule_OutputConfig;
struct PWMModule_OutputPolarity {
/**
* PxA, PxC active-high; PxB, PxD active-high
*/
char ACTIVE_HIGH_ACTIVE_HIGH;
/**
* PxA, PxC active-high; PxB, PxD active-low
*/
char ACTIVE_HIGH_ACTIVE_LOW;
/**
* PxA, PxC active-low; PxB, PxD active-high
*/
char ACTIVE_LOW_ACTIVE_HIGH;
/**
* PxA, PxC active-low; PxB, PxD active-low
*/
char ACTIVE_LOW_ACTIVE_LOW;
};
extern const struct PWMModule_OutputPolarity PWMModule_OutputPolarity;
// ----------------------------------------------------------------------------
// FixedVoltageReference
// ----------------------------------------------------------------------------
struct FixedVoltageReference_Buffer1Reference {
char OFF;
char OUTPUT_1x;
char OUTPUT_2x;
char OUTPUT_4x;
};
extern const struct FixedVoltageReference_Buffer1Reference FixedVoltageReference_Buffer1Reference;
struct FixedVoltageReference_Buffer2Reference {
char OFF;
char OUTPUT_1x;
char OUTPUT_2x;
char OUTPUT_4x;
};
extern const struct FixedVoltageReference_Buffer2Reference FixedVoltageReference_Buffer2Reference;
// ----------------------------------------------------------------------------
// USART
// ----------------------------------------------------------------------------
#include "USART.h"
struct EUSART_Mode {
/**
* Asynchronous mode.
*/
char ASYNCHRONOUS;
/**
* Synchronous master mode.
*/
char SYNCHRONOUS_MASTER;
/**
* Synchronous slave mode.
*/
char SYNCHRONOUS_SLAVE;
};
extern const struct EUSART_Mode EUSART_Mode;
struct EUSART_ReceiveMode {
/**
* 8bit reception mode.
*/
char EIGHT_BIT;
/**
* 9bit reception mode.
*/
char NINE_BIT;
/**
* 9bit reception mode with address detection (asynchronous mode only)
*/
char NINE_BIT_ADDRESS_DETECTION;
};
extern const struct EUSART_ReceiveMode EUSART_ReceiveMode;
struct EUSART_TransmitMode {
/**
* 8bit transmission mode.
*/
char EIGHT_BIT;
/**
* 9bit transmission mode.
*
* This mode is used for address detection.
*/
char NINE_BIT;
};
extern const struct EUSART_TransmitMode EUSART_TransmitMode;
struct EUSART_Polarity {
/**
* Non inverted in asynchronous mode, falling edge in synchronous mode.
*/
char NON_INVERTED_OR_FALLING_EDGE;
/**
* Inverted in asynchronous mode, rising edge in synchronous mode.
*/
char INVERTED_OR_RISING_EDGE;
};
extern const struct EUSART_Polarity EUSART_Polarity;
struct EUSART_Error {
/**
* Framing error mask.
*/
char FRAMING;
/**
* Overrun error mask.
*/
char OVERRUN;
};
extern const struct EUSART_Error EUSART_Error;
// ----------------------------------------------------------------------------
// MSSP
// ----------------------------------------------------------------------------
#include "I2C.h"
struct I2C_SlewRateControl {
/**
* Slew rate control enabled for high speed mode (400 kHz)
*/
char ENABLE;
/**
* Slew rate control disabled for standard speed mode
* (100 kHz and 1 MHz)
*/
char DISABLE;
};
extern const struct I2C_SlewRateControl I2C_SlewRateControl;
struct I2C_InputThreshold {
/**
* Disable SMbus specific inputs
*/
char DEFAULT;
/**
* Enable input logic so that thresholds are compliant
* with SMbus specification
*/
char SMBUS;
};
extern const struct I2C_InputThreshold I2C_InputThreshold;
struct I2C_GeneralCallInterrupt {
/**
* General call address disabled
*/
char DISABLE;
/**
* Enable interrupt when a general call address (0x00 or 00h)
* is received in the SSPxSR
*/
char ENABLE;
};
extern const struct I2C_GeneralCallInterrupt I2C_GeneralCallInterrupt;
struct I2C_ConditionInterrupt {
/**
* Start and Stop detection interrupts are disabled
*/
char DISABLE;
/**
* Enable interrupt on detection of Start or Restart conditions
*/
char START;
/**
* Enable interrupt on detection of Stop condition
*/
char STOP;
/**
* Enable interrupt on detection of Start or Restart or Stop conditions
*/
char START_AND_STOP;
};
extern const struct I2C_ConditionInterrupt I2C_ConditionInterrupt;
struct I2C_SDAHoldTime {
/**
* Minimum of 100 ns hold time on SDAx after the falling edge of SCLx
*/
char ONE_HUNDRED_NS;
/**
* Minimum of 300 ns hold time on SDAx after the falling edge of SCLx
*/
char THREE_HUNDRED_NS;
};
extern const struct I2C_SDAHoldTime I2C_SDAHoldTime;
struct I2C_SlaveBusCollisionDetect {
char DISABLE;
char ENABLE;
};
extern const struct I2C_SlaveBusCollisionDetect I2C_SlaveBusCollisionDetect;
struct I2C_ClockStretch {
char ADDRESS;
char DATA;
char ADDRESS_AND_DATA;
char DISABLE;
};
extern const struct I2C_ClockStretch I2C_ClockStretch;
/**
* Hardware peripheral definition.
*/
struct Hardware {
/**
* Interrupt service constructor.
*/
const struct InterruptService* (*ADConverterInterruptService)();
const struct InterruptService* (*Timer0InterruptService)();
const struct InterruptService* (*Timer1InterruptService)();
const struct InterruptService* (*Timer1GateControlInterruptService)();
const struct InterruptService* (*Timer2InterruptService)();
const struct InterruptService* (*Timer4InterruptService)();
const struct InterruptService* (*Timer6InterruptService)();
const struct InterruptService* (*CCP1InterruptService)();
const struct InterruptService* (*CCP2InterruptService)();
const struct InterruptService* (*CCP3InterruptService)();
const struct InterruptService* (*CCP4InterruptService)();
/**
* Configure alternate pin function.
*
* @param RX and DT
* @param SDO
* @param SS
* @param T1G
* @param TX and CK
* @param P1D
* @param P1C
* @param P2B
* @param CCP2
*/
void (*configureAlternatePinFunction)(char, char, char, char, char, char, char, char, char);
/**
* Configure oscillator module.
*
* @param identifier of internal clock frequency
* @param identifier of phase locked loop
* @param identifier of system clock source
*/
void (*configureOscillator)(char, char, char);
const struct IOPort* (*PortA)();
const struct IOPort* (*PortC)();
/**
* AD converter constructor.
*
* @param positie reference
* @param negative reference
* @param conversion clock
*/
const struct ADConverter* (*ADConverterModule)(char, char, char);
/**
* Timer0 constructor.
*
* @param clock source
* @param prescaler
*/
const TimerModule* (*Timer0)(char, char);
/**
* Timer1 constructor.
*
* @param clock source
* @param prescaler
*/
const TimerModule* (*Timer1)(char, char);
/**
* Timer1 gate control constructor.
*
* @param source
* @param mode
*/
const TimerGateControl* (*Timer1GateControl)(char, char);
/**
* Timer2/4/6 constructor.
*
* @param prescaler
* @param postscaler
* @param period count
*/
const TimerModule* (*Timer2)(char, char, uint8_t);
const TimerModule* (*Timer4)(char, char, uint8_t);
const TimerModule* (*Timer6)(char, char, uint8_t);
/**
* Capture1/2/3/4 constructor.
*
* @param mode
*/
const struct Capture* (*Capture1Module)(char);
const struct Capture* (*Capture2Module)(char);
const struct Capture* (*Capture3Module)(char);
const struct Capture* (*Capture4Module)(char);
/**
* Compare1/2/3/4 constructor.
*
* @param mode
*/
const struct Compare* (*Compare1Module)(char);
const struct Compare* (*Compare2Module)(char);
const struct Compare* (*Compare3Module)(char);
const struct Compare* (*Compare4Module)(char);
/**
* PWM1/2 constructor.
*
* @param base timer
* @param output config
* @param output polarity
*/
const struct PWM* (*EnhancedPWM1Module)(char, char, char);
const struct PWM* (*EnhancedPWM2Module)(char, char, char);
/**
* PWM3/4 constructor
*
* @param base timer
* @param output polarity
*/
const struct PWM* (*PWM3Module)(char, char);
const struct PWM* (*PWM4Module)(char, char);
/**
* Configure fixed voltage reference.
*
* @param buffer1 reference
* @param buffer2 reference
*/
void (*configureFixedVoltageReference)(char, char);
/**
* Universal receiver transmitter constructor.
*
* @param operating mode
* @param receive mode
* @param transmit mode
* @param polarity
* @param baudrate
*/
const struct USART* (*EUSART)(char, char, char, char, unsigned long);
};
/**
* Hardware singleton instance.
* This is declared at Hardware.c
*/
extern const struct Hardware Hardware;
#endif /* HARDWARE_H */
|
k-ishigaki/Linesensor2017
|
src/application/PhotoTransistor.h
|
#ifndef PHOTO_TRANSISTOR_H
#define PHOTO_TRANSISTOR_H
struct PhotoTransistor {
int (*read)(void);
};
#endif /* PHOTO_TRANSISTOR_H */
|
k-ishigaki/Linesensor2017
|
src/application/main.c
|
<reponame>k-ishigaki/Linesensor2017
#include <xc.h>
#include "Hardware.h"
#include "LineSensor.h"
#include <stdbool.h>
#include <stdio.h>
#define _XTAL_FREQ OPERATING_FREQUENCY
// RA0 and RA1 are used for debug serial port
// (RA0 : TX, RA1 : RX)
#define RA0_A0_PIN 0b00000001
#define RA1_A1_PIN 0b00000010
#define RA2_A2_PIN 0b00000100
#define RA4_A3_PIN 0b00010000
#define RA5_nSW_PIN 0b00100000
#define RC0_SCL_PIN 0b00000001
#define RC1_SDA_PIN 0b00000010
#define RC2_D0_PIN 0b00000100
#define RC3_D1_PIN 0b00001000
#define RC4_D2_PIN 0b00010000
#define RC5_D3_PIN 0b00100000
static const struct USART* serial;
static const struct LED* leds[4];
static const struct PhotoTransistor* photoTrs[4];
void putch(char data) {
serial->write(data);
}
void setup() {
Hardware.configureAlternatePinFunction(
AlternatePinFunction_RXAndDT.RA1,
AlternatePinFunction_SDO.RA4,
AlternatePinFunction_SS.RA3,
AlternatePinFunction_T1G.RA3,
AlternatePinFunction_TXAndCK.RA0,
AlternatePinFunction_P1D.RC0,
AlternatePinFunction_P1C.RC1,
AlternatePinFunction_P2B.RA4,
AlternatePinFunction_CCP2.RA5);
Hardware.configureOscillator(
OscillatorModule_InternalClockFrequency.HF_8MHz,
OscillatorModule_PhaseLockedLoop.ENABLE,
OscillatorModule_SystemClockSource.DETERMINED_BY_CONFIG);
// get line sensor hardware instances
leds[0] = LineSensor.getLED0();
leds[1] = LineSensor.getLED1();
leds[2] = LineSensor.getLED2();
leds[3] = LineSensor.getLED3();
photoTrs[0] = LineSensor.getPhotoTransistor0();
photoTrs[1] = LineSensor.getPhotoTransistor1();
photoTrs[2] = LineSensor.getPhotoTransistor2();
photoTrs[3] = LineSensor.getPhotoTransistor3();
const struct IOPort* portA = Hardware.PortA();
const struct IOPort* portC = Hardware.PortC();
// switch input pin
portA->setPinModes(
RA5_nSW_PIN,
IOPort_PinMode.DIGITAL_INPUT_WITH_INTERNAL_PULLUP);
// debug serial TX pin
portA->setPinModes(RA0_A0_PIN, IOPort_PinMode.DIGITAL_OUTPUT);
// debug serial RX pin
portA->setPinModes(RA1_A1_PIN, IOPort_PinMode.DIGITAL_INPUT);
// debug serial settings
serial = Hardware.EUSART(
EUSART_Mode.ASYNCHRONOUS,
EUSART_ReceiveMode.EIGHT_BIT,
EUSART_TransmitMode.EIGHT_BIT,
EUSART_Polarity.NON_INVERTED_OR_FALLING_EDGE,
115200L);
// i2c pins
portC->setPinModes(
RC0_SCL_PIN | RC1_SDA_PIN,
IOPort_PinMode.ANALOG_INPUT);
}
void loop() {
for (int i = 0; i < 100; i++) {
__delay_ms(10);
}
leds[3]->turnOn();
for (int i = 0; i < 10; i++) {
__delay_ms(10);
}
printf("res = %d\r\n", photoTrs[2]->read());
leds[3]->turnOff();
// if(!(portA->read() & RA5_nSW_PIN)) {
// printf("pushed\r\n");
// }
serial->write('A');
serial->write('B');
serial->write('C');
serial->write('D');
serial->write('\n');
}
int main(void) {
setup();
while(true) {
loop();
}
}
|
k-ishigaki/Linesensor2017
|
src/hardware/OscillatorModule.c
|
#include <xc.h>
#include "Hardware.h"
// ----------------------------------------------------------------------------
// OscillatorModule_InternalClockFrequency
// ----------------------------------------------------------------------------
enum OscillatorModule_InternalClockFrequency_Constants {
HF_16MHz = 0b1111,
HF_8MHz = 0b1110,
HF_4MHz = 0b1101,
HF_2MHz = 0b1100,
HF_1MHz = 0b1011,
HF_500kHz = 0b1010,
HF_250kHz = 0b1001,
HF_125kHz = 0b1000,
MF_500kHz = 0b0111,
MF_250kHz = 0b0110,
MF_125kHz = 0b0101,
MF_62500Hz = 0b0100,
HF_31250Hz = 0b0011,
MF_31250Hz = 0b0010,
LF_31kHz = 0b0001,
};
const struct OscillatorModule_InternalClockFrequency OscillatorModule_InternalClockFrequency = {
HF_16MHz,
HF_8MHz,
HF_4MHz,
HF_2MHz,
HF_1MHz,
HF_500kHz,
HF_250kHz,
HF_125kHz,
MF_500kHz,
MF_250kHz,
MF_125kHz,
MF_62500Hz,
HF_31250Hz,
MF_31250Hz,
LF_31kHz,
};
// ----------------------------------------------------------------------------
// OscillatorModule_PhaseLockedLoop
// ----------------------------------------------------------------------------
enum OscillatorModule_PhaseLockedLoop_Constants {
ENABLE = 1,
DISABLE = 0,
};
const struct OscillatorModule_PhaseLockedLoop OscillatorModule_PhaseLockedLoop = {
ENABLE,
DISABLE,
};
// ----------------------------------------------------------------------------
// OscillatorModule_SystemClockSource
// ----------------------------------------------------------------------------
enum OscillatorModule_SystemClockSource_Constants {
INTERNAL = 0b10,
SECONDARY = 0b01,
DETERMINED_BY_CONFIG = 0b00,
};
const struct OscillatorModule_SystemClockSource OscillatorModule_SystemClockSource = {
INTERNAL,
SECONDARY,
DETERMINED_BY_CONFIG,
};
void OscillatorModule_configure(
char internalClockFrequency,
char phaseLockedLoop,
char systemClockSource) {
OSCCONbits.IRCF = internalClockFrequency;
OSCCONbits.SPLLEN = phaseLockedLoop;
OSCCONbits.SCS = systemClockSource;
}
|
k-ishigaki/Linesensor2017
|
src/hardware/MSSP.c
|
#include <xc.h>
#include "Hardware.h"
const struct I2C_SlewRateControl I2C_SlewRateControl = {
0, // ENABLE
1, // DISABLE
};
const struct I2C_InputThreshold I2C_InputThreshold = {
0, // DEFAULT
1, // SMBUS
};
const struct I2C_GeneralCallInterrupt I2C_GeneralCallInterrupt = {
0, // DISABLE
1, // ENABLE
};
const struct I2C_ConditionInterrupt I2C_ConditionInterrupt = {
0b00, // DISABLE
0b01, // START
0b10, // STOP
0b11, // START_AND_STOP
};
const struct I2C_SDAHoldTime I2C_SDAHoldTime = {
0, // ONE_HUNDRED_NS
1, // THREE_HUNDRED_NS
};
const struct I2C_SlaveBusCollisionDetect I2C_SlaveBusCollisionDetect = {
0, // DISABLE
1, // ENABLE
};
#define this_(name) MSSPI2C_##name
static uint8_t this_(sspm_slave);
static uint8_t this_(sspm_master);
static uint8_t this_(sspadd_slave);
static uint16_t this_(slaveAddress);
static void this_(generateStartCondition)() {
SSP1CON2bits.SEN = 1;
}
static void this_(generateStopCondition)() {
SSP1CON2bits.PEN = 1;
}
static void this_(generateRestartCondition)() {
SSP1CON2bits.RSEN = 1;
}
static bool this_(isPending)() {
bool result;
if ((SSP1CON1bits.SSPM & 0b1110) == 0b1110) {
// in slave mode
result = !(PIR1bits.SSP1IF);
} else {
// in master mode
result = !(PIR1bits.SSP1IF) || SSP1CON2bits.PEN || SSP1CON2bits.RSEN || SSP1CON2bits.SEN;
}
if (result == false) {
PIR1bits.SSP1IF = 0;
}
return result;
}
static void this_(startTransmission)(uint8_t data) {
// store data to buffer and start transmission
SSP1BUF = data;
}
static bool this_(wasAcknowledged)() {
return !(SSP1CON2bits.ACKSTAT);
}
static void this_(startReception)(bool nextAck) {
PIR1bits.SSP1IF = 0;
// next acknowledge is enabled by ACKDT = 0
SSP1CON2bits.ACKDT = nextAck == true ? 0 : 1;
// start reception
SSP1CON2bits.RCEN = 1;
}
static uint8_t this_(read)() {
// read data from buffer
return SSP1BUF;
}
static const struct I2C this_(instance) = {
this_(generateStartCondition),
this_(generateStopCondition),
this_(generateRestartCondition),
this_(isPending),
this_(startTransmission),
this_(wasAcknowledged),
this_(startReception),
this_(read),
};
const struct I2C* this_(constructor)(
char slewRateControll,
char inputThreshold,
unsigned int clockPeriod,
uint16_t slaveAddress,
char generalCallInterrupt,
char conditionInterrupt,
char sdaHoldTime) {
SSP1STATbits.SMP = slewRateControll;
SSP1STATbits.CKE = inputThreshold;
this_(slaveAddress) = slaveAddress;
this_(sspm_slave) = this_(slaveAddress) > 0x7F ? 0b0111 : 0b0110;
return &this_(instance);
}
|
k-ishigaki/Linesensor2017
|
src/hardware/EUSART.c
|
#include <xc.h>
#include "Hardware.h"
// ----------------------------------------------------------------------------
// EUSART constants
// ----------------------------------------------------------------------------
enum EUSART_Mode_Constant {
ASYNCHRONOUS,
SYNCHRONOUS_MASTER,
SYNCHRONOUS_SLAVE,
};
const struct EUSART_Mode EUSART_Mode = {
ASYNCHRONOUS,
SYNCHRONOUS_MASTER,
SYNCHRONOUS_SLAVE,
};
enum EUSART_ReceiveMode_Constant {
R_EIGHT_BIT = 0b00,
R_NINE_BIT = 0b01,
R_NINE_BIT_ADDRESS_DETECTION = 0b11,
};
const struct EUSART_ReceiveMode EUSART_ReceiveMode = {
R_EIGHT_BIT,
R_NINE_BIT,
R_NINE_BIT_ADDRESS_DETECTION,
};
enum EUSART_TransmitMode_Constant {
T_EIGHT_BIT = 0,
T_NINE_BIT = 1,
};
const struct EUSART_TransmitMode EUSART_TransmitMode = {
T_EIGHT_BIT,
T_NINE_BIT,
};
enum EUSART_Polarity_Constant {
NON_INVERTED_OR_FALLING_EDGE = 0,
INVERTED_OR_RISING_EDGE = 1,
};
const struct EUSART_Polarity EUSART_Polarity = {
NON_INVERTED_OR_FALLING_EDGE,
INVERTED_OR_RISING_EDGE,
};
enum EUSART_Error_Constant {
FRAMING = 0b10,
OVERRUN = 0b01,
};
const struct EUSART_Error EUSART_Error = {
FRAMING,
OVERRUN,
};
// ----------------------------------------------------------------------------
// EUSART interface
// ----------------------------------------------------------------------------
#define EUSART_(name) EUSART_##name
static uint16_t EUSART_(read)() {
// RCSTA<0> = RX9D
return RCREG + ((uint16_t)(RCSTA & 0b00000001) << 8);
}
static bool EUSART_(hasReceived)() {
return PIR1bits.RCIF;
}
static void EUSART_(write)(uint16_t data) {
while(!TXSTAbits.TRMT);
TXSTAbits.TX9D = data >> 8;
TXREG = data;
}
static bool EUSART_(isTransmitting)() {
return !TXSTAbits.TRMT;
}
static void EUSART_(resetReceiver)() {
RCSTAbits.SPEN = 0;
RCSTAbits.SPEN = 1;
}
static uint8_t EUSART_(getErrors)() {
// get FERR bit and OERR bit
// RCSTA<2> = FERR
// RCSTA<1> = OERR
return (RCSTA & 0b00000110) >> 1;
}
static const struct USART EUSART_(instance) = {
EUSART_(read),
EUSART_(hasReceived),
EUSART_(write),
EUSART_(isTransmitting),
EUSART_(resetReceiver),
EUSART_(getErrors),
};
// ----------------------------------------------------------------------------
// EUSART constructor
// ----------------------------------------------------------------------------
const struct USART* EUSART_(constructor)(
char mode,
char receiveMode,
char transmitMode,
char polarity,
unsigned long baudrate){
// only asynchronous mode can be used
// decide receive mode and transmit mode
RCSTAbits.RX9 = receiveMode;
RCSTAbits.ADDEN = receiveMode >> 1;
TXSTAbits.TX9 = transmitMode;
// decide polarity
BAUDCONbits.SCKP = polarity;
// decide baudrate
uint16_t spbrg = OPERATING_FREQUENCY / (4 * baudrate) - 1;
SPBRGH = spbrg >> 8;
SPBRGL = spbrg;
BAUDCONbits.BRG16 = 1;
TXSTAbits.BRGH = 1;
// enable serial port
TXSTAbits.TXEN = 1;
RCSTAbits.CREN = 1;
RCSTAbits.SPEN = 1;
// return instance
return &EUSART_(instance);
}
|
k-ishigaki/Linesensor2017
|
src/application/LineSensor.h
|
#ifndef LINE_SENSOR_H
#define LINE_SENSOR_H
#include "LED.h"
#include "PhotoTransistor.h"
struct LineSensor {
const struct LED* (*getLED0)(void); // left edge
const struct PhotoTransistor* (*getPhotoTransistor0)(void);
const struct LED* (*getLED1)(void);
const struct PhotoTransistor* (*getPhotoTransistor1)(void);
const struct LED* (*getLED2)(void);
const struct PhotoTransistor* (*getPhotoTransistor2)(void);
const struct LED* (*getLED3)(void);
const struct PhotoTransistor* (*getPhotoTransistor3)(void);
// const struct LED* (*getLED0)(void); // right edge
};
extern const struct LineSensor LineSensor;
#endif /* LINE_SENSOR_H */
|
k-ishigaki/Linesensor2017
|
src/hardware/NativeInterrupts.c
|
#include <xc.h>
/*
* To increase registerable number of interrupts,
* you can increase LIST_SIZE constant.
*/
#include "Hardware.h"
// dummy instances, priority constants, interrupt vector
// are declared once.
#ifndef DECRARING_INTERRUPT_SERVICE_COMMON
#define DECRARING_INTERRUPT_SERVICE_COMMON
enum {
LIST_SIZE = 8,
};
// ----------------------------------------------------------------------------
// dummy instances
// ----------------------------------------------------------------------------
static void handler_dummy() {
// do nothing
}
static void InterruptListener_onInterrupt() {
// do nothing
}
static const struct InterruptListener listener_dummy = {
InterruptListener_onInterrupt,
};
// ----------------------------------------------------------------------------
// InterruptVector
// ----------------------------------------------------------------------------
/** interrupt handlers */
static void (*handlers[LIST_SIZE])() = {&handler_dummy};
/** number of registered handlers */
static unsigned char numOfHandlers = 0;
/** hardware interrupt service routine (ISR) */
static void __interrupt isr() {
for(unsigned char i = 0; i < numOfHandlers; i++) {
handlers[i]();
}
}
/** register handler (void function pointer) to interrupt vector */
static void registerHandler(void (*handler)()) {
// If argument handler has been already registered to vector;
// remove it and register again.
for(unsigned char i = 0; i < numOfHandlers; i++) {
if(handlers[i] == handler) {
numOfHandlers--;
}
}
handlers[numOfHandlers] = handler;
numOfHandlers++;
}
#endif /* DECRARING_INTERRUPT_SERVICE_COMMON */
// ----------------------------------------------------------------------------
// InterruptService
// ----------------------------------------------------------------------------
#if !defined(AD_CONVERTER_MODULE_INTERRUPT_SERVICE_DECLARED)
#define AD_CONVERTER_MODULE_INTERRUPT_SERVICE_DECLARED
#define InterruptService_(name) ADConverterModuleInterruptService_##name
#define PIRbit PIR1bits.ADIF
#define PIEbit PIE1bits.ADIE
#elif !defined(TIMER0_MODULE_INTERRUPT_SERVICE_DECLARED)
#define TIMER0_MODULE_INTERRUPT_SERVICE_DECLARED
#define InterruptService_(name) Timer0ModuleInterruptService_##name
#define PIRbit INTCONbits.TMR0IF
#define PIEbit INTCONbits.TMR0IE
#elif !defined(TIMER1_MODULE_INTERRUPT_SERVICE_DECLARED)
#define TIMER1_MODULE_INTERRUPT_SERVICE_DECLARED
#define InterruptService_(name) Timer1ModuleInterruptService_##name
#define PIRbit PIR1bits.TMR1IF
#define PIEbit PIE1bits.TMR1IE
#elif !defined(TIMER1_GATE_CONTROL_INTERRUPT_SERVICE_DECLARED)
#define TIMER1_GATE_CONTROL_INTERRUPT_SERVICE_DECLARED
#define InterruptService_(name) Timer1GateControlInterruptService_##name
#define PIRbit PIR1bits.TMR1GIF
#define PIEbit PIE1bits.TMR1GIE
#elif !defined(TIMER2_MODULE_INTERRUPT_SERVICE_DECLARED)
#define TIMER2_MODULE_INTERRUPT_SERVICE_DECLARED
#define InterruptService_(name) Timer2ModuleInterruptService_##name
#define PIRbit PIR1bits.TMR2IF
#define PIEbit PIE1bits.TMR2IE
#elif !defined(TIMER4_MODULE_INTERRUPT_SERVICE_DECLARED)
#define TIMER4_MODULE_INTERRUPT_SERVICE_DECLARED
#define InterruptService_(name) Timer4ModuleInterruptService_##name
#define PIRbit PIR3bits.TMR4IF
#define PIEbit PIE3bits.TMR4IE
#elif !defined(TIMER6_MODULE_INTERRUPT_SERVICE_DECLARED)
#define TIMER6_MODULE_INTERRUPT_SERVICE_DECLARED
#define InterruptService_(name) Timer6ModuleInterruptService_##name
#define PIRbit PIR3bits.TMR6IF
#define PIEbit PIE3bits.TMR6IE
#elif !defined(CCP1_MODULE_INTERRUPT_SERVICE_DECLARED)
#define CCP1_MODULE_INTERRUPT_SERVICE_DECLARED
#define InterruptService_(name) CCP1ModuleInterruptService_##name
#define PIRbit PIR1bits.CCP1IF
#define PIEbit PIE1bits.CCP1IE
#elif !defined(CCP2_MODULE_INTERRUPT_SERVICE_DECLARED)
#define CCP2_MODULE_INTERRUPT_SERVICE_DECLARED
#define InterruptService_(name) CCP2ModuleInterruptService_##name
#define PIRbit PIR2bits.CCP2IF
#define PIEbit PIE2bits.CCP2IE
#elif !defined(CCP3_MODULE_INTERRUPT_SERVICE_DECLARED)
#define CCP3_MODULE_INTERRUPT_SERVICE_DECLARED
#define InterruptService_(name) CCP3ModuleInterruptService_##name
#define PIRbit PIR3bits.CCP3IF
#define PIEbit PIE3bits.CCP3IE
#elif !defined(CCP4_MODULE_INTERRUPT_SERVICE_DECLARED)
#define CCP4_MODULE_INTERRUPT_SERVICE_DECLARED
#define InterruptService_(name) CCP4ModuleInterruptService_##name
#define PIRbit PIR3bits.CCP4IF
#define PIEbit PIE3bits.CCP4IE
#define EXIT_LOOP
#endif
static const struct InterruptListener* InterruptService_(listener) = &listener_dummy;
static void InterruptService_(handleInterrupt)() {
if(PIRbit && PIEbit) {
InterruptService_(listener)->onInterrupt();
PIRbit = 0;
}
}
static void InterruptService_(registerListener)(
const struct InterruptListener* listener) {
InterruptService_(listener) = listener;
registerHandler(&InterruptService_(handleInterrupt));
}
static void InterruptService_(enableInterrupt)() {
PIRbit = 0;
PIEbit = 1;
}
static void InterruptService_(disableInterrupt)() {
PIEbit = 0;
PIRbit = 0;
}
static const struct InterruptService InterruptService_(instance) = {
InterruptService_(registerListener),
InterruptService_(enableInterrupt),
InterruptService_(disableInterrupt),
};
const struct InterruptService* InterruptService_(constructor)() {
return &InterruptService_(instance);
}
#undef InterruptService_
#undef PIRbit
#undef PIEbit
#ifndef EXIT_LOOP
#include "NativeInterrupts.c"
#endif /* EXIT_LOOP */
|
k-ishigaki/Linesensor2017
|
src/hardware/CCPModule.c
|
#include <xc.h>
#include "Hardware.h"
#ifndef CCP_MODULE_COMMON
#define CCP_MODULE_COMMON
// ----------------------------------------------------------------------------
// CaptureModule Constants
// ----------------------------------------------------------------------------
enum CaptureModule_Mode_Constants {
EVERY_FALLING_EDGE = 0b0100,
EVERY_RISING_EDGE = 0b0101,
EVERY_4TH_RISING_EDGE = 0b0110,
EVERY_16TH_RISING_EDGE = 0b0111,
};
const struct CaptureModule_Mode CaptureModule_Mode = {
EVERY_FALLING_EDGE,
EVERY_RISING_EDGE,
EVERY_4TH_RISING_EDGE,
EVERY_16TH_RISING_EDGE,
};
enum CompareModule_Mode_Constants {
LOW_TO_HIGH = 0b1000,
HIGH_TO_LOW = 0b1001,
SOFTWARE_INTERRUPT = 0b1010,
SPECIAL_EVENT_TRIGGER = 0b1011,
};
const struct CompareModule_Mode CompareModule_Mode = {
LOW_TO_HIGH,
HIGH_TO_LOW,
SOFTWARE_INTERRUPT,
SPECIAL_EVENT_TRIGGER,
};
enum PWMModule_BaseTimer_Constants {
TIMER2 = 0b00,
TIMER4 = 0b01,
TIMER6 = 0b10,
};
const struct PWMModule_BaseTimer PWMModule_BaseTimer = {
TIMER2,
TIMER4,
TIMER6,
};
enum PWMModule_OutputConfig_Constants {
SINGLE = 0b00,
FULL_BRIDGE_FORWARD = 0b01,
HALF_BRIDGE = 0b10,
FULL_BRIDGE_REVERCE = 0b11,
};
const struct PWMModule_OutputConfig PWMModule_OutputConfig = {
SINGLE,
FULL_BRIDGE_FORWARD,
HALF_BRIDGE,
FULL_BRIDGE_REVERCE,
};
enum PWMModule_OutputPolarity_Constants {
ACTIVE_HIGH_ACTIVE_HIGH = 0b1100,
ACTIVE_HIGH_ACTIVE_LOW = 0b1101,
ACTIVE_LOW_ACTIVE_HIGH = 0b1110,
ACTIVE_LOW_ACTIVE_LOW = 0b1111,
};
const struct PWMModule_OutputPolarity PWMModule_OutputPolarity = {
ACTIVE_HIGH_ACTIVE_HIGH,
ACTIVE_HIGH_ACTIVE_LOW,
ACTIVE_LOW_ACTIVE_HIGH,
ACTIVE_LOW_ACTIVE_LOW,
};
#endif
#ifndef CCP1_MODULE_DECLARED
#define CCP1_MODULE_DECLARED
#define CCPxM CCP1CONbits.CCP1M
#define CxTSEL CCPTMRSbits.C1TSEL
#define DCxB CCP1CONbits.DC1B
#define CCPRxL CCPR1L
#define CCPRxH CCPR1H
#define PxM CCP1CONbits.P1M
#define CaptureModule_(name) CaptureModule1_##name
#define CompareModule_(name) CompareModule1_##name
#define PWMModule_(name) PWMModule1_##name
#elif !defined(CCP2_MODULE_DECLARED)
#define CCP2_MODULE_DECLARED
#define CCPxM CCP2CONbits.CCP2M
#define CxTSEL CCPTMRSbits.C2TSEL
#define DCxB CCP2CONbits.DC2B
#define CCPRxL CCPR2L
#define CCPRxH CCPR2H
#define PxM CCP2CONbits.P2M
#define CaptureModule_(name) CaptureModule2_##name
#define CompareModule_(name) CompareModule2_##name
#define PWMModule_(name) PWMModule2_##name
#elif !defined(CCP3_MODULE_DECLARED)
#define CCP3_MODULE_DECLARED
#define CCPxM CCP3CONbits.CCP3M
#define CxTSEL CCPTMRSbits.C3TSEL
#define DCxB CCP3CONbits.DC3B
#define CCPRxL CCPR3L
#define CCPRxH CCPR3H
#define CaptureModule_(name) CaptureModule3_##name
#define CompareModule_(name) CompareModule3_##name
#define PWMModule_(name) PWMModule3_##name
#elif !defined(CCP4_MODULE_DECLARED)
#define CCP4_MODULE_DECLARED
#define CCPxM CCP4CONbits.CCP4M
#define CxTSEL CCPTMRSbits.C4TSEL
#define DCxB CCP4CONbits.DC4B
#define CCPRxL CCPR4L
#define CCPRxH CCPR4H
#define CaptureModule_(name) CaptureModule4_##name
#define CompareModule_(name) CompareModule4_##name
#define PWMModule_(name) PWMModule4_##name
#define EXIT_LOOP
#endif
// ----------------------------------------------------------------------------
// CaptureModule
// ----------------------------------------------------------------------------
static uint16_t CaptureModule_(getCapturedCount)() {
return ((uint16_t)CCPRxH << 8) + CCPRxL;
}
static const struct Capture CaptureModule_(instance) = {
CaptureModule_(getCapturedCount),
};
const struct Capture* CaptureModule_(constructor)(
char mode) {
CCPxM = mode;
return &CaptureModule_(instance);
}
void CaptureModule_(destructor)() {
CCPxM = 0;
}
// ----------------------------------------------------------------------------
// CompareModule
// ----------------------------------------------------------------------------
static void CompareModule_(setComparedCount)(uint16_t count) {
CCPRxH = count >> 8;
CCPRxL = count;
}
static const struct Compare CompareModule_(instance) = {
CompareModule_(setComparedCount),
};
const struct Compare* CompareModule_(constructor)(
char mode) {
CCPxM = mode;
return &CompareModule_(instance);
}
void CompareModule_(destructor)() {
CCPxM = 0;
}
// ----------------------------------------------------------------------------
// PWMModule
// ----------------------------------------------------------------------------
static void PWMModule_(setDutyCycle)(uint16_t dutyCycle) {
CCPRxL = dutyCycle >> 2;
DCxB = dutyCycle;
}
static const struct PWM PWMModule_(instance) = {
PWMModule_(setDutyCycle),
};
#ifdef PxM
const struct PWM* PWMModule_(constructor)(
char baseTimer,
char outputConfig,
char outputPolarity) {
CxTSEL = baseTimer;
PxM = outputConfig;
CCPxM = outputPolarity;
return &PWMModule_(instance);
}
#else
const struct PWM* PWMModule_(constructor)(
char baseTimer,
char outputPolarity) {
CxTSEL = baseTimer;
// CCP4 and CCP5 don't have configurable output (single output only).
CCPxM = outputPolarity;
return &PWMModule_(instance);
}
#endif
void PWMModule_(destructor)() {
CCPxM = 0;
}
#undef CCPxM
#undef CxTSEL
#undef DCxB
#undef CCPRxL
#undef CCPRxH
#undef PxM
#undef CaptureModule_
#undef CompareModule_
#undef PWMModule_
#ifndef EXIT_LOOP
#include "CCPModule.c"
#endif
|
k-ishigaki/Linesensor2017
|
src/application/AnalogInputPin.h
|
#ifndef ANALOG_INPUT_PIN_H
#define ANALOG_INPUT_PIN_H
struct AnalogInputPin {
int (*read)(void);
};
#endif /* ANALOG_INPUT_PIN_H */
|
k-ishigaki/Linesensor2017
|
src/hardware/Hardware.c
|
#include "Hardware.h"
// declared at InterruptVector.c
extern const struct InterruptService* ADConverterModuleInterruptService_constructor();
extern const struct InterruptService* Timer0ModuleInterruptService_constructor();
extern const struct InterruptService* Timer1ModuleInterruptService_constructor();
extern const struct InterruptService* Timer1GateControlInterruptService_constructor();
extern const struct InterruptService* Timer2ModuleInterruptService_constructor();
extern const struct InterruptService* Timer4ModuleInterruptService_constructor();
extern const struct InterruptService* Timer6ModuleInterruptService_constructor();
extern const struct InterruptService* CCP1ModuleInterruptService_constructor();
extern const struct InterruptService* CCP2ModuleInterruptService_constructor();
extern const struct InterruptService* CCP3ModuleInterruptService_constructor();
extern const struct InterruptService* CCP4ModuleInterruptService_constructor();
extern const struct InterruptService* CCP5ModuleInterruptService_constructor();
// declared at OscillatorModule.c
extern void OscillatorModule_configure(char, char, char);
// declared at AlternatePinFunction.c
extern void AlternatePinFunction_configure(char, char, char, char, char, char, char, char, char);
// declared at IOPort.c
extern const struct IOPort* PortA_constructor();
extern const struct IOPort* PortC_constructor();
// declared at ADConverterModule.c
extern const struct ADConverter* ADConverterModule_constructor(char, char, char);
// declared at TimerModule.c
extern const TimerModule* Timer0Module_constructor(char, char);
extern const TimerModule* Timer1Module_constructor(char, char);
extern const TimerGateControl* Timer1GateControl_constructor(char, char);
extern const TimerModule* Timer2Module_constructor(char, char, uint8_t);
extern const TimerModule* Timer4Module_constructor(char, char, uint8_t);
extern const TimerModule* Timer6Module_constructor(char, char, uint8_t);
// declared at CCPModule.c
extern const struct Capture* CaptureModule1_constructor(char);
extern const struct Capture* CaptureModule2_constructor(char);
extern const struct Capture* CaptureModule3_constructor(char);
extern const struct Capture* CaptureModule4_constructor(char);
extern const struct Compare* CompareModule1_constructor(char);
extern const struct Compare* CompareModule2_constructor(char);
extern const struct Compare* CompareModule3_constructor(char);
extern const struct Compare* CompareModule4_constructor(char);
extern const struct PWM* PWMModule1_constructor(char, char, char);
extern const struct PWM* PWMModule2_constructor(char, char, char);
extern const struct PWM* PWMModule3_constructor(char, char);
extern const struct PWM* PWMModule4_constructor(char, char);
// declared at FixedVoltageReference.c
extern void FixedVoltageReference_configure(char, char);
// declared at EUSART.c
extern const struct USART* EUSART_constructor(char, char, char, char, unsigned long);
const struct Hardware Hardware = {
ADConverterModuleInterruptService_constructor,
Timer0ModuleInterruptService_constructor,
Timer1ModuleInterruptService_constructor,
Timer1GateControlInterruptService_constructor,
Timer2ModuleInterruptService_constructor,
Timer4ModuleInterruptService_constructor,
Timer6ModuleInterruptService_constructor,
CCP1ModuleInterruptService_constructor,
CCP2ModuleInterruptService_constructor,
CCP3ModuleInterruptService_constructor,
CCP4ModuleInterruptService_constructor,
AlternatePinFunction_configure,
OscillatorModule_configure,
PortA_constructor,
PortC_constructor,
ADConverterModule_constructor,
Timer0Module_constructor,
Timer1Module_constructor,
Timer1GateControl_constructor,
Timer2Module_constructor,
Timer4Module_constructor,
Timer6Module_constructor,
CaptureModule1_constructor,
CaptureModule2_constructor,
CaptureModule3_constructor,
CaptureModule4_constructor,
CompareModule1_constructor,
CompareModule2_constructor,
CompareModule3_constructor,
CompareModule4_constructor,
PWMModule1_constructor,
PWMModule2_constructor,
PWMModule3_constructor,
PWMModule4_constructor,
FixedVoltageReference_configure,
EUSART_constructor,
};
|
k-ishigaki/Linesensor2017
|
src/application/PhotoTransistor.c
|
#include "PhotoTransistor.h"
#include "AnalogInputPin.h"
#ifndef COMMON_DECLARATION
#define COMMON_DECLARATION
static int read_dummy() {
return 0;
}
static const struct AnalogInputPin AnalogInputPin_dummy = {
read_dummy,
};
static const struct PhotoTransistor* PhotoTransistor0_constructor(const struct AnalogInputPin*);
static const struct PhotoTransistor* PhotoTransistor1_constructor(const struct AnalogInputPin*);
static const struct PhotoTransistor* PhotoTransistor2_constructor(const struct AnalogInputPin*);
static const struct PhotoTransistor* PhotoTransistor3_constructor(const struct AnalogInputPin*);
static const struct PhotoTransistor* (*PhotoTransistorn_constructor[4])(const struct AnalogInputPin*) = {
PhotoTransistor0_constructor,
PhotoTransistor1_constructor,
PhotoTransistor2_constructor,
PhotoTransistor3_constructor,
};
const struct PhotoTransistor* createPhotoTransistor(
const struct AnalogInputPin* pin) {
static char index = 0;
return PhotoTransistorn_constructor[index++](
pin);
}
#endif /* COMMON_DECLARATION */
#if !defined(PHOTO_TRANSISTOR0_DECLARED)
#define PHOTO_TRANSISTOR0_DECLARED
#define this_(name) PhotoTransistor0_##name
#elif !defined(PHOTO_TRANSISTOR1_DECLARED)
#define PHOTO_TRANSISTOR1_DECLARED
#define this_(name) PhotoTransistor1_##name
#elif !defined(PHOTO_TRANSISTOR2_DECLARED)
#define PHOTO_TRANSISTOR2_DECLARED
#define this_(name) PhotoTransistor2_##name
#elif !defined(PHOTO_TRANSISTOR3_DECLARED)
#define PHOTO_TRANSISTOR3_DECLARED
#define this_(name) PhotoTransistor3_##name
#define EXIT_LOOP
#endif
static const struct AnalogInputPin* this_(pin);
static int this_(read)() {
return this_(pin)->read();
}
static const struct PhotoTransistor this_(instance) = {
this_(read),
};
static const struct PhotoTransistor* this_(constructor)(
const struct AnalogInputPin* pin) {
this_(pin) = &AnalogInputPin_dummy;
this_(pin) = pin;
return &this_(instance);
}
#undef this_
#if !defined(EXIT_LOOP)
#include "PhotoTransistor.c"
#endif
|
k-ishigaki/Linesensor2017
|
src/application/DigitalPin.c
|
#include "DigitalPin.h"
#include <stdint.h>
#include "IOPort.h"
#ifndef COMMON_DECLARATION
#define COMMON_DECLARATION
static void setPinModes_dummy(uint8_t pos, char mode) {
}
static uint8_t read_dummy(void) {
return 0;
}
static void write_dummy(uint8_t pos, uint8_t output) {
}
static void toggle_dummy(uint8_t pos) {
}
static const struct IOPort IOPort_dummy = {
setPinModes_dummy,
read_dummy,
write_dummy,
toggle_dummy,
};
static const struct DigitalPin* DigitalPin0_constructor(const struct IOPort*, char, char, char);
static const struct DigitalPin* DigitalPin1_constructor(const struct IOPort*, char, char, char);
static const struct DigitalPin* DigitalPin2_constructor(const struct IOPort*, char, char, char);
static const struct DigitalPin* DigitalPin3_constructor(const struct IOPort*, char, char, char);
static const struct DigitalPin* DigitalPin4_constructor(const struct IOPort*, char, char, char);
static const struct DigitalPin* DigitalPin5_constructor(const struct IOPort*, char, char, char);
static const struct DigitalPin* DigitalPin6_constructor(const struct IOPort*, char, char, char);
static const struct DigitalPin* DigitalPin7_constructor(const struct IOPort*, char, char, char);
static const struct DigitalPin* (*DigitalPin_constructor[8])(const struct IOPort*, char, char, char) = {
DigitalPin0_constructor,
DigitalPin1_constructor,
DigitalPin2_constructor,
DigitalPin3_constructor,
DigitalPin4_constructor,
DigitalPin5_constructor,
DigitalPin6_constructor,
DigitalPin7_constructor,
};
const struct DigitalPin* createDigitalPin(
const struct IOPort* port,
char position,
char inputPinMode,
char outputPinMode) {
static char index = 0;
return DigitalPin_constructor[index++](
port,
position,
inputPinMode,
outputPinMode);
}
#endif /* COMMON_DECLARATION */
#if !defined(DIGITAL_PIN0_DECLARED)
#define DIGITAL_PIN0_DECLARED
#define this_(name) DigitalPin0_##name
#elif !defined(DIGITAL_PIN1_DECLARED)
#define DIGITAL_PIN1_DECLARED
#define this_(name) DigitalPin1_##name
#elif !defined(DIGITAL_PIN2_DECLARED)
#define DIGITAL_PIN2_DECLARED
#define this_(name) DigitalPin2_##name
#elif !defined(DIGITAL_PIN3_DECLARED)
#define DIGITAL_PIN3_DECLARED
#define this_(name) DigitalPin3_##name
#elif !defined(DIGITAL_PIN4_DECLARED)
#define DIGITAL_PIN4_DECLARED
#define this_(name) DigitalPin4_##name
#elif !defined(DIGITAL_PIN5_DECLARED)
#define DIGITAL_PIN5_DECLARED
#define this_(name) DigitalPin5_##name
#elif !defined(DIGITAL_PIN6_DECLARED)
#define DIGITAL_PIN6_DECLARED
#define this_(name) DigitalPin6_##name
#elif !defined(DIGITAL_PIN7_DECLARED)
#define DIGITAL_PIN7_DECLARED
#define this_(name) DigitalPin7_##name
#define EXIT_LOOP
#endif
static const struct IOPort* this_(port);
static char this_(position);
static char this_(inputMode);
static char this_(outputMode);
static void this_(setDirection)(bool direction) {
if (direction == false) {
this_(port)->setPinModes(
this_(position),
this_(inputMode));
} else {
this_(port)->setPinModes(
this_(position),
this_(outputMode));
}
}
static bool this_(read)() {
if ((this_(port)->read() & this_(position)) == 0) {
return false;
} else {
return true;
}
}
static void this_(write)(bool value) {
if (value == true) {
this_(port)->write(
this_(position),
0xFF);
} else {
this_(port)->write(
this_(position),
0x00);
}
}
static const struct DigitalPin this_(instance) = {
this_(setDirection),
this_(read),
this_(write),
};
static const struct DigitalPin* this_(constructor)(
const struct IOPort* port,
char position,
char inputPinMode,
char outputPinMode) {
this_(port) = &IOPort_dummy;
this_(port) = port;
this_(position) = position;
this_(inputMode) = inputPinMode;
this_(outputMode) = outputPinMode;
return &this_(instance);
}
#undef this_
#if !defined(EXIT_LOOP)
#include "DigitalPin.c"
#endif
|
k-ishigaki/Linesensor2017
|
src/hardware/ADConverterModule.c
|
<reponame>k-ishigaki/Linesensor2017
#include <xc.h>
#include "Hardware.h"
// ----------------------------------------------------------------------------
// ADConverterModule_PositiveReference
// ----------------------------------------------------------------------------
enum ADConverterModule_PositiveReference_Constants {
FVR = 0b11,
VREF_PLUS = 0b10,
VDD = 0b00,
};
const struct ADConverterModule_PositiveReference
ADConverterModule_PositiveReference = {
FVR,
VREF_PLUS,
VDD,
};
// ----------------------------------------------------------------------------
// ADConverterModule_NegativeReference
// ----------------------------------------------------------------------------
enum ADConverterModule_NegativeReference_Constants {
VREF_MINUS = 0b1,
VSS = 0b0,
};
const struct ADConverterModule_NegativeReference
ADConverterModule_NegativeReference = {
VREF_MINUS,
VSS,
};
// ----------------------------------------------------------------------------
// ADConverterModule_ConversionClock
// ----------------------------------------------------------------------------
enum ADConverterModule_ConversionClock_Constants {
F_RC = 0b011,
F_OSC_DIV_64 = 0b110,
F_OSC_DIV_32 = 0b010,
F_OSC_DIV_16 = 0b101,
F_OSC_DIV_8 = 0b001,
F_OSC_DIV_4 = 0b100,
F_OSC_DIV_2 = 0b000,
};
const struct ADConverterModule_ConversionClock
ADConverterModule_ConversionClock = {
F_RC,
F_OSC_DIV_64,
F_OSC_DIV_32,
F_OSC_DIV_16,
F_OSC_DIV_8,
F_OSC_DIV_4,
F_OSC_DIV_2,
};
// ----------------------------------------------------------------------------
// ADConverterModule_InputChannel
// ----------------------------------------------------------------------------
enum ADConverterModule_InputChannel_Constants {
FVR_BUFFER_1 = 0b11111,
DAC = 0b11110,
TEMPERATURE_INDICATOR = 0b11101,
AN7 = 0b00111,
AN6 = 0b00110,
AN5 = 0b00101,
AN4 = 0b00100,
AN3 = 0b00011,
AN2 = 0b00010,
AN1 = 0b00001,
AN0 = 0b00000,
};
const struct ADConverterModule_InputChannel ADConverterModule_InputChannel = {
FVR_BUFFER_1,
DAC,
TEMPERATURE_INDICATOR,
AN7,
AN6,
AN5,
AN4,
AN3,
AN2,
AN1,
AN0,
};
// ----------------------------------------------------------------------------
// ADConverterModule
// ----------------------------------------------------------------------------
#define ADConverterModule_(name) ADConverterModule_##name
static void ADConverterModule_(selectInputChannel)(char channel) {
ADCON0bits.CHS = channel;
}
static void ADConverterModule_(startConversion)() {
while(ADCON0bits.GO);
ADCON0bits.GO = 1;
}
static bool ADConverterModule_(isConverting)() {
return ADCON0bits.GO;
}
static uint16_t ADConverterModule_(getResult)() {
return ((unsigned int)ADRESH << 2) + (ADRESL >> 6);
}
static const struct ADConverter ADConverterModule_(instance) = {
ADConverterModule_selectInputChannel,
ADConverterModule_startConversion,
ADConverterModule_isConverting,
ADConverterModule_getResult,
};
const struct ADConverter* ADConverterModule_(constructor)(
char positiveReference,
char negativeReference,
char conversionClock) {
ADCON1bits.ADPREF = positiveReference;
ADCON1bits.ADNREF = negativeReference;
ADCON1bits.ADCS = conversionClock;
ADCON0bits.ADON = 1;
return &ADConverterModule_(instance);
}
|
k-ishigaki/Linesensor2017
|
src/application/LED.c
|
#include "LED.h"
#include "DigitalPin.h"
#include <stdbool.h>
#ifndef COMMON_DECLARATION
#define COMMON_DECLARATION
static void setDirection_dummy(bool direction) {
}
static bool read_dummy() {
return false;
}
static void write_dummy(bool value) {
}
static const struct DigitalPin DigitalPin_dummy = {
setDirection_dummy,
read_dummy,
write_dummy,
};
static const struct LED* LED0_constructor(const struct DigitalPin*);
static const struct LED* LED1_constructor(const struct DigitalPin*);
static const struct LED* LED2_constructor(const struct DigitalPin*);
static const struct LED* LED3_constructor(const struct DigitalPin*);
static const struct LED* (*LEDn_constructor[4])(const struct DigitalPin*) = {
LED0_constructor,
LED1_constructor,
LED2_constructor,
LED3_constructor,
};
const struct LED* createLED(const struct DigitalPin* pin) {
static char index = 0;
return LEDn_constructor[index++](pin);
}
#endif /* COMMON_DECLARATION */
#if !defined(LED0_DECLARED)
#define LED0_DECLARED
#define LEDn_(name) LED0_##name
#elif !defined(LED1_DECLARED)
#define LED1_DECLARED
#define LEDn_(name) LED1_##name
#elif !defined(LED2_DECLARED)
#define LED2_DECLARED
#define LEDn_(name) LED2_##name
#elif !defined(LED3_DECLARED)
#define LED3_DECLARED
#define LEDn_(name) LED3_##name
#define EXIT_LOOP
#endif
static const struct DigitalPin* LEDn_(pin);
static void LEDn_(turnOn)() {
LEDn_(pin)->write(true);
}
static void LEDn_(turnOff)() {
LEDn_(pin)->write(false);
}
static const struct LED LEDn_(instance) = {
LEDn_(turnOn),
LEDn_(turnOff),
};
static const struct LED* LEDn_(constructor)(const struct DigitalPin* pin) {
LEDn_(pin) = &DigitalPin_dummy;
LEDn_(pin) = pin;
LEDn_(pin)->setDirection(true);
return &LEDn_(instance);
}
#undef LEDn_
#if !defined(EXIT_LOOP)
#include "LED.c"
#endif
|
MasterIceZ/genlib
|
genlib.h
|
#include<bits/stdc++.h>
#include "testlib.h"
using namespace std;
namespace util{
bool isPrime(int u){
if(u <= 1){
return false;
}
if(u <= 3){
return true;
}
if(u % 2 == 0 || u % 3 == 0){
return false;
}
for(int i=5; i*i<=u; i+=6){
if(u % i == 0 || u % (i + 2) == 0){
return false;
}
}
return true;
}
vector<int> sieveoferathos(int l, int r){
vector<int> ret;
unordered_map<int, int> mp;
l = max(2, l);
for(int i=l; i<=r; ++i){
if(isPrime(i)){
break;
}
l++;
}
for(int i=l; i<=r; ++i){
if(!mp[i]){
ret.push_back(i);
for(int j=i*i; j<=r; j+=i){
mp[j] = 1;
}
}
}
return ret;
}
vector<int> generate_prime(int l, int r){
vector<int> res;
for(int i=l; i<=r; ++i){
if(isPrime(i)){
res.push_back(i);
}
}
return res;
}
long long hash_size(long long now){
vector<long long> st = {
53, 97, 193, 389, 769, 1543, 3079, 6151, 12289, 24593,
49157, 98317, 196613, 393241, 786433, 1572869, 3145739,
6291469, 12582917, 25165843, 50331653, 100663319,
201326611, 402653189, 805306457, 1610612741
};
return st[upper_bound(st.begin(), st.end(), now) - (st.begin())];
}
long long nCr(long long n, long long r){
if(r == 0 || n == 1 || r == n){
return 1;
}
return nCr(n-1, r-1) + nCr(n-1, r);
}
}
string rand_str(int sz=1, char l='a', char r='z'){
string s;
for(int i=1; i<=sz; ++i){
char newchr = (char)rnd.next(l, r);
s += newchr;
}
return s;
}
int rand_prime(int l=1, int r=100){
vector<int> v = util::generate_prime(l, r);
return v[(int)rnd.next(0, (int)v.size() - 1)];
}
set<tuple<int, int>> gen_tree(int n, bool print = true){
set<tuple<int, int>> s;
for(int i=2; i<=n; ++i){
int u = rnd.next(1, i - 1), v = i;
if(u == v){
continue;
}
if(print){
printf("%d %d\n", u, v);
}
s.emplace(u, v);
}
return s;
}
set<tuple<int, int>> gen_connected_graph(int n, int m, bool print = true){
set<tuple<int, int>> s;
for(int i=1; i<n; ++i){
if(print){
printf("%d %d\n", i, i+1);
}
s.emplace(i, i + 1);
}
while((int)s.size() != m){
int a = rnd.next(1, n), b = rnd.next(1, n);
int u = min(a, b), v = max(a, b);
if(u == v || s.count(make_tuple(u, v))){
continue;
}
if(print){
printf("%d %d\n", u, v);
}
s.emplace(u, v);
}
return s;
}
set<tuple<int, int>> gen_graph(int n, int m, bool print = true){
set<tuple<int, int>> s;
while((int)s.size() != m){
int a = rnd.next(1, n), b = rnd.next(1, n);
int u = min(a, b), v = max(a, b);
if(u == v || s.count(make_tuple(u, v))){
continue;
}
if(print){
printf("%d %d\n", u, v);
}
s.emplace(u, v);
}
return s;
}
set<tuple<int, int>> gen_complete_graph(int n, bool print = true){
set<tuple<int, int>> s;
for(int i=1; i<=n; ++i){
for(int j=i+1; j<=n; ++j){
if(print){
printf("%d %d\n", i, j);
}
s.emplace(i, j);
}
}
return s;
}
vector<vector<char>> gen_table(int n, int m, char a, char b, bool print = true){
vector<vector<char>> t(n + 1, vector<char>(m + 1));
for(int i=1; i<=n; ++i){
for(int j=1; j<=m; ++j){
int r = rnd.next(1, 2);
t[i][j] = r % 2 ? a : b;
if(print){
printf("%c", t[i][j]);
}
}
if(print){
printf("\n");
}
}
return t;
}
string gen_palindrome(size_t sz, bool upper_case = false, bool print = true) {
char l = 'a', r = 'z';
if(upper_case){
l = 'A', r = 'Z';
}
string new_chr = rand_str(1, l, r);
string middle = new_chr + (sz % 2 ? "" : new_chr);
int prefix_size = (sz + 1) / 2;
string prefix = rand_str(prefix_size, l, r);
string suffix = prefix;
reverse(suffix.begin(), suffix.end());
string palindrome = prefix + middle + suffix;
if(print) {
printf("%s\n", palindrome.c_str());
}
return palindrome;
}
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDCollectionImageElement.h
|
<reponame>indragiek/WWDC-2014
//
// INDCollectionImageElement.h
// <NAME>
//
// Created by <NAME> on 2014-04-09.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import <Mantle/Mantle.h>
/**
* Collection view element model representing image content.
*/
@interface INDCollectionImageElement : MTLModel <MTLJSONSerializing>
/**
* Image name of the standard (small) image.
*/
@property (nonatomic, copy, readonly) NSString *imageName;
/**
* Image name of the full image.
*/
@property (nonatomic, copy, readonly) NSString *bigImageName;
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDAboutViewController.h
|
<reponame>indragiek/WWDC-2014
//
// INDAboutViewController.h
// <NAME>
//
// Created by <NAME> on 2014-04-09.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import "INDStaticCollectionViewController.h"
/**
* View controller for the about view.
*/
@interface INDAboutViewController : INDStaticCollectionViewController
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDCollectionTimelineMilestoneElement.h
|
<gh_stars>10-100
//
// INDCollectionTimelineMilestoneElement.h
// <NAME>
//
// Created by <NAME> on 2014-04-09.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import "INDCollectionTextElement.h"
/**
* Collection view element model representing a timeline milestone.
*/
@interface INDCollectionTimelineMilestoneElement : INDCollectionTextElement <MTLJSONSerializing>
/**
* Image representing the milestone.
*/
@property (nonatomic, strong, readonly) UIImage *image;
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDStaticCollectionViewController.h
|
//
// INDStaticCollectionViewController.h
// <NAME>
//
// Created by <NAME> on 2014-04-10.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import "INDJSONCollectionViewController.h"
/**
* Collection view controller that displays static content from "element" model objects.
*/
@interface INDStaticCollectionViewController : INDJSONCollectionViewController
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDCollectionTimelineMilestoneCellView.h
|
<gh_stars>10-100
//
// INDCollectionTimelineMilestoneCellView.h
// <NAME>
//
// Created by <NAME> on 2014-04-09.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import "INDCollectionTextCellView.h"
/**
* Content view for a collection view cell that shows a milestone in a timeline.
*/
@interface INDCollectionTimelineMilestoneCellView : INDCollectionTextCellView
/**
* Image view that shows an image representing the milestone.
*/
@property (nonatomic, weak) IBOutlet UIImageView *imageView;
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDCollectionTextElement.h
|
<reponame>indragiek/WWDC-2014
//
// INDCollectionTextElement.h
// <NAME>
//
// Created by <NAME> on 2014-04-09.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import <Mantle/Mantle.h>
/**
* Collection view element model representing text content.
*/
@interface INDCollectionTextElement : MTLModel <MTLJSONSerializing>
/**
* Attributed text by parsing the HTML.
*/
@property (nonatomic, copy, readonly) NSAttributedString *attributedText;
/**
* Line spacing to be set on the label displaying the text.
*/
@property (nonatomic, assign, readonly) CGFloat lineSpacing;
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDJSONModelAdapter.h
|
//
// INDJSONModelAdapter.h
// <NAME>
//
// Created by <NAME> on 2014-04-07.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
/**
* Adapter for converting arrays of model objects between JSON and object representations.
*/
@interface INDJSONModelAdapter : NSObject
/**
* Converts an array of model objects to an array of JSON dictionaries.
*
* @param objects Array of `MTLModel` objects conforming to `MTLJSONSerializing`
*
* @return An array of JSON dictionaries representing the model objects.
*/
+ (NSArray *)JSONArrayForModelObjects:(NSArray *)objects;
/**
* Converts an array of JSON dictionaries to an array of model objects.
*
* @param JSONArray Array of JSON dictionaries previously created by using
* `+JSONArrayForModelObjects:`
*
* @return An array of `MTLModel` objects conforming to `MTLJSONSerializing`.
*/
+ (NSArray *)modelObjectsFromJSONArray:(NSArray *)JSONArray;
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDCollectionTimelineMilestoneMarker.h
|
<filename>Indragie Karunaratne/Classes/INDCollectionTimelineMilestoneMarker.h
//
// INDCollectionTimelineMilestoneMarker.h
// <NAME>
//
// Created by <NAME> on 2014-04-09.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
/**
* Draws a timeline milestone marker.
*/
@interface INDCollectionTimelineMilestoneMarker : UIView
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Categories/NSJSONSerialization+INDAdditions.h
|
//
// NSJSONSerialization+INDAdditions.h
// <NAME>
//
// Created by <NAME> on 2014-04-09.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSJSONSerialization (INDAdditions)
/**
* Deserializes JSON from a .json resource file included in the app bundle.
*
* @param name The name of the JSON file in the main bundle, without file extension.
* @param options Options for reading the JSON data and creating the Foundation objects.
* @param error If an error occurs, upon return contains an NSError object that describes the problem.
*
* @return A Foundation object from the JSON data in data, or nil if an error occurs.
*/
+ (id)ind_deserializeJSONObjectFromContentsOfFileName:(NSString *)name error:(NSError **)error;
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDMainCellView.h
|
//
// INDMainCellView.h
// <NAME>
//
// Created by <NAME> on 2014-04-07.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import "INDLineSpacingLabel.h"
/**
* Content view for table view cells in the main view.
*/
@interface INDMainCellView : UIView
/**
* Image view that shows the background image.
*/
@property (nonatomic, weak) IBOutlet UIImageView *backgroundImageView;
/**
* Image view that shows the icon for the project.
*/
@property (nonatomic, weak) IBOutlet UIImageView *iconImageView;
/**
* Label to show the title of the project.
*/
@property (nonatomic, weak) IBOutlet UILabel *titleLabel;
/**
* Label to show a description for the project.
*/
@property (nonatomic, weak) IBOutlet INDLineSpacingLabel *descriptionLabel;
/**
* View shown when the cell is highlighted.
*/
@property (nonatomic, weak) IBOutlet UIView *highlightOverlayView;
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDHTMLToAttributedStringValueTransformer.h
|
//
// INDHTMLToAttributedStringValueTransformer.h
// <NAME>
//
// Created by <NAME> on 2014-04-09.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
extern NSString * const INDHTMLToAttributedStringValueTransformerName;
/**
* A value transformer that converts an HTML string to an `NSAttributedString`
*/
@interface INDHTMLToAttributedStringValueTransformer : NSValueTransformer
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDMainViewController.h
|
<gh_stars>10-100
//
// INDMainViewController.h
// <NAME>
//
// Created by <NAME> on 2014-04-07.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import "INDJSONTableViewController.h"
@interface INDMainViewController : INDJSONTableViewController
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDCollectionButton.h
|
<reponame>indragiek/WWDC-2014<gh_stars>10-100
//
// INDCollectionButton.h
// <NAME>
//
// Created by <NAME> on 2014-04-10.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
/**
* UIButton subclass used by `INDCollectionButtonCellView`.
*/
@interface INDCollectionButton : UIButton
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDCollectionVideoPlayerView.h
|
//
// INDCollectionVideoPlayerView.h
// <NAME>
//
// Created by <NAME> on 2014-04-10.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import <AVFoundation/AVFoundation.h>
/**
* A view that plays a video using `AVPlayerLayer` and repeats it when playback
* has ended.
*/
@interface INDCollectionVideoPlayerView : UIView
/**
* Player used for video playback.
*/
@property (nonatomic, strong) AVPlayer *player;
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDCollectionVideoCellViewController.h
|
<filename>Indragie Karunaratne/Classes/INDCollectionVideoCellViewController.h
//
// INDCollectionVideoCellViewController.h
// <NAME>
//
// Created by <NAME> on 2014-04-10.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import "MNSHostedViewController.h"
/**
* View controller for collection view video cell.
*/
@interface INDCollectionVideoCellViewController : MNSHostedViewController
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDCollectionTimelineMilestoneCellViewController.h
|
//
// INDCollectionTimelineMilestoneCellViewController.h
// <NAME>
//
// Created by <NAME> on 2014-04-09.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import "INDCollectionTextCellViewController.h"
/**
* View controller for timeline milestone cell.
*/
@interface INDCollectionTimelineMilestoneCellViewController : INDCollectionTextCellViewController
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDCollectionTimelineEndpointMarker.h
|
//
// INDCollectionTimelineEndpointMarker.h
// <NAME>
//
// Created by <NAME> on 2014-04-09.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
/**
* Draws a marker that shows the start or end of a timeline.
*/
@interface INDCollectionTimelineEndpointMarker : UIView
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDMainCellViewController.h
|
<reponame>indragiek/WWDC-2014
//
// INDMainCellViewController.h
// <NAME>
//
// Created by <NAME> on 2014-04-07.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import "MNSHostedViewController.h"
@interface INDMainCellViewController : MNSHostedViewController
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDCollectionButtonCellView.h
|
//
// INDCollectionButtonCellView.h
// <NAME>
//
// Created by <NAME> on 2014-04-10.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
/**
* Content view for a collection view cell that displays a button.
*/
@interface INDCollectionButtonCellView : UIView
@property (nonatomic, weak) IBOutlet UIButton *button;
/**
* URL to open when the button is tapped.
*/
@property (nonatomic, strong) NSURL *url;
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDMainViewItem.h
|
//
// INDMainViewItem.h
// <NAME>
//
// Created by <NAME> on 2014-04-07.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import <Mantle/Mantle.h>
/**
* Model object class for the table view items on the main view.
*/
@interface INDMainViewItem : MTLModel <MTLJSONSerializing>
/**
* Title of the project.
*/
@property (nonatomic, copy, readonly) NSString *title;
/**
* Short description of the project.
*/
@property (nonatomic, copy, readonly) NSString *projectDescription;
/**
* Project icon.
*/
@property (nonatomic, strong, readonly) UIImage *iconImage;
/**
* Background image for the project.
*/
@property (nonatomic, strong, readonly) UIImage *backgroundImage;
/**
* Class of the view controller that displays the content for this item.
*/
@property (nonatomic, readonly) Class viewControllerClass;
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDCollectionVideoElement.h
|
<filename>Indragie Karunaratne/Classes/INDCollectionVideoElement.h
//
// INDCollectionVideoElement.h
// <NAME>
//
// Created by <NAME> on 2014-04-10.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import <Mantle/Mantle.h>
/**
* Collection view element model representing a video.
*/
@interface INDCollectionVideoElement : MTLModel <MTLJSONSerializing>
/**
* Video URL.
*/
@property (nonatomic, strong, readonly) NSURL *url;
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDCollectionImageCellViewController.h
|
<reponame>indragiek/WWDC-2014<filename>Indragie Karunaratne/Classes/INDCollectionImageCellViewController.h
//
// INDCollectionImageCellViewController.h
// <NAME>
//
// Created by <NAME> on 2014-04-09.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import "MNSHostedViewController.h"
/**
* View controller for collection view image cell.
*/
@interface INDCollectionImageCellViewController : MNSHostedViewController
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDMainViewFooterView.h
|
<filename>Indragie Karunaratne/Classes/INDMainViewFooterView.h
//
// INDMainViewFooterView.h
// <NAME>
//
// Created by <NAME> on 2014-04-09.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
@protocol INDMainViewFooterViewDelegate;
/**
* Footer for the table view containing social buttons.
*/
@interface INDMainViewFooterView : UIView
@property (nonatomic, strong, readonly) UIButton *githubButton;
@property (nonatomic, strong, readonly) UIButton *twitterButton;
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDLineSpacingLabel.h
|
//
// INDLineSpacingLabel.h
// <NAME>
//
// Created by <NAME> on 2014-04-07.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import "MNSMultilineLabel.h"
/**
* UILabel subclass with adjustable line spacing.
*/
@interface INDLineSpacingLabel : UILabel
/**
* Line spacing.
*
* Naming this property `lineSpacing` breaks `UILabel`. Private property?
*/
@property (nonatomic, assign) CGFloat ind_lineSpacing;
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDCollectionTextCellView.h
|
//
// INDCollectionTextCellView.h
// <NAME>
//
// Created by <NAME> on 2014-04-09.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import "INDLineSpacingLabel.h"
/**
* Content view for a collection view cell that displays attributed text.
*/
@interface INDCollectionTextCellView : UIView
@property (nonatomic, weak) IBOutlet INDLineSpacingLabel *label;
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDUserInterfaceDefinitions.h
|
<reponame>indragiek/WWDC-2014<filename>Indragie Karunaratne/Classes/INDUserInterfaceDefinitions.h
//
// INDUserInterfaceDefinitions.h
// <NAME>
//
// Created by <NAME> on 2014-04-07.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#ifndef __IND_UI_DEFINITIONS__
#define __IND_UI_DEFINITIONS__
//////////////
// General //
//////////////
#define IND_TRANSITION_ANIMATION_DURATION 0.25
#define IND_COLLECTION_BUTTON_BORDER_COLOR [UIColor colorWithRed:0.59 green:0.59 blue:0.59 alpha:1.0]
#define IND_COLLECTION_BUTTON_BORDER_RADIUS 5.0
#define IND_COLLECTION_BUTTON_BORDER_WIDTH 1.0
#define IND_COLLECTION_BUTTON_BG_COLOR [UIColor clearColor]
#define IND_COLLECTION_BUTTON_H_BG_COLOR [UIColor colorWithRed:0.59 green:0.59 blue:0.59 alpha:1.0]
#define IND_COLLECTION_BUTTON_TEXT_COLOR [UIColor blackColor]
#define IND_COLLECTION_BUTTON_H_TEXT_COLOR [UIColor whiteColor]
//////////////////////////
// Main view controller //
//////////////////////////
#define IND_MAIN_BAR_TINT_COLOR [UIColor colorWithRed:0.29 green:0.29 blue:0.29 alpha:1.0]
#define IND_MAIN_TINT_COLOR [UIColor whiteColor]
#define IND_MAIN_DESCRIPTION_LINE_SPACING 2.f
#define IND_MAIN_TWITTER_BG_COLOR [UIColor colorWithRed:0.00 green:0.69 blue:0.93 alpha:1.0]
#define IND_MAIN_GITHUB_BG_COLOR [UIColor blackColor]
///////////////////////////
// About view controller //
///////////////////////////
#define IND_ABOUT_TITLE_COLOR [UIColor blackColor]
//////////////////////////////
// Flamingo view controller //
//////////////////////////////
#define IND_FLAMINGO_BAR_TINT_COLOR [UIColor colorWithRed:0.97 green:0.39 blue:0.41 alpha:1.0]
#define IND_FLAMINGO_TINT_COLOR [UIColor whiteColor]
////////////////////////////
// Sonora view controller //
////////////////////////////
#define IND_SONORA_BAR_TINT_COLOR [UIColor colorWithRed:0.38 green:0.35 blue:0.80 alpha:1.0]
#define IND_SONORA_TINT_COLOR [UIColor whiteColor]
#endif
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDAppDelegate.h
|
<gh_stars>10-100
//
// INDAppDelegate.h
// <NAME>
//
// Created by <NAME> on 2014-04-07.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface INDAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDCollectionVideoCellView.h
|
//
// INDCollectionVideoCellView.h
// <NAME>
//
// Created by <NAME> on 2014-04-10.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import "INDCollectionVideoPlayerView.h"
/**
* Content view for a collection view cell that displays a video.
*/
@interface INDCollectionVideoCellView : UIView
/**
* Inline video player view.
*/
@property (nonatomic, weak) IBOutlet INDCollectionVideoPlayerView *playerView;
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDSonoraViewController.h
|
<gh_stars>10-100
//
// INDSonoraViewController.h
// <NAME>
//
// Created by <NAME> on 2014-04-11.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import "INDStaticCollectionViewController.h"
@interface INDSonoraViewController : INDStaticCollectionViewController
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDCollectionButtonElement.h
|
<gh_stars>10-100
//
// INDCollectionButtonElement.h
// <NAME>
//
// Created by <NAME> on 2014-04-10.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import <Mantle/Mantle.h>
/**
* Collection view element model representing a button that links to a URL.
*/
@interface INDCollectionButtonElement : MTLModel <MTLJSONSerializing>
/**
* Title text of the button.
*/
@property (nonatomic, copy, readonly) NSString *title;
/**
* URL that the button opens when tapped.
*/
@property (nonatomic, strong, readonly) NSURL *url;
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDCollectionTextCellViewController.h
|
<filename>Indragie Karunaratne/Classes/INDCollectionTextCellViewController.h<gh_stars>10-100
//
// INDCollectionTextCellViewController.h
// <NAME>
//
// Created by <NAME> on 2014-04-09.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import "MNSHostedViewController.h"
/**
* View controller for collection view attributed text cell.
*/
@interface INDCollectionTextCellViewController : MNSHostedViewController
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDFlamingoViewController.h
|
//
// INDFlamingoViewController.h
// <NAME>
//
// Created by <NAME> on 2014-04-10.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import "INDStaticCollectionViewController.h"
/**
* View controller for the Flamingo detail view.
*/
@interface INDFlamingoViewController : INDStaticCollectionViewController
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDNavigationController.h
|
//
// INDNavigationController.h
// <NAME>
//
// Created by <NAME> on 2014-04-07.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface INDNavigationController : UINavigationController
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDJSONTableViewController.h
|
//
// INDJSONTableViewController.h
// <NAME>
//
// Created by <NAME> on 2014-04-07.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import "MNSTableViewController.h"
#import "MNSViewControllerRegistrar.h"
/**
* Table view controller driven by JSON files as the data source.
*/
@interface INDJSONTableViewController : MNSTableViewController
/**
* Loads table view data from JSON loaded from a file.
*
* This method searches for JSON files in the main bundle.
*
* @param fileName The name of the JSON file to load data from. The file should
* contain a JSON array of model objects constructed using `INDJSONModelAdapter`.
*
*/
- (void)reloadDataWithJSONFileName:(NSString *)fileName;
/**
* Model objects displayed in the table view.
*/
@property (nonatomic, strong, readonly) NSArray *objects;
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDCollectionTimelineFooterViewController.h
|
<gh_stars>10-100
//
// INDCollectionTimelineFooterViewController.h
// <NAME>
//
// Created by <NAME> on 2014-04-09.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import "MNSHostedViewController.h"
/**
* View controller for a timeline footer.
*/
@interface INDCollectionTimelineFooterViewController : MNSHostedViewController
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDImageNameToImageValueTransformer.h
|
<reponame>indragiek/WWDC-2014
//
// INDImageNameToImageValueTransformer.h
// <NAME>
//
// Created by <NAME> on 2014-04-07.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
extern NSString * const INDImageNameToImageValueTransformerName;
/**
* A value transformer that converts image names <-> images.
*/
@interface INDImageNameToImageValueTransformer : NSValueTransformer
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDCollectionTimelineFooterElement.h
|
//
// INDCollectionTimelineFooterElement.h
// <NAME>
//
// Created by <NAME> on 2014-04-09.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import <Mantle/Mantle.h>
/**
* Empty model object that represents the footer of a timeline.
*/
@interface INDCollectionTimelineFooterElement : MTLModel <MTLJSONSerializing>
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDCollectionImageCellView.h
|
//
// INDCollectionImageCellView.h
// <NAME>
//
// Created by <NAME> on 2014-04-09.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
/**
* Content view for a collection view cell that displays an image.
*/
@interface INDCollectionImageCellView : UIView
/**
* Image view used to display the image inline.
*/
@property (nonatomic, weak) IBOutlet UIImageView *imageView;
/**
* Name of a big image to open on tap.
*/
@property (nonatomic, copy) NSString *bigImageName;
@end
|
indragiek/WWDC-2014
|
Indragie Karunaratne/Classes/INDSocialButton.h
|
//
// INDSocialButton.h
// <NAME>
//
// Created by <NAME> on 2014-04-07.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
/**
* Custom button that shows a social service icon, name, and caret.
*/
@interface INDSocialButton : UIButton
@end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.