id
int64 4
16.3M
| file_name
stringlengths 3
68
| file_path
stringlengths 14
181
| content
stringlengths 39
9.06M
| size
int64 39
9.06M
| language
stringclasses 1
value | extension
stringclasses 2
values | total_lines
int64 1
711k
| avg_line_length
float64 3.18
138
| max_line_length
int64 10
140
| alphanum_fraction
float64 0.02
0.93
| repo_name
stringlengths 7
69
| repo_stars
int64 2
61.6k
| repo_forks
int64 12
7.81k
| repo_open_issues
int64 0
1.13k
| repo_license
stringclasses 10
values | repo_extraction_date
stringclasses 657
values | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 1
class | exact_duplicates_redpajama
bool 1
class | exact_duplicates_githubcode
bool 2
classes | near_duplicates_stackv2
bool 1
class | near_duplicates_stackv1
bool 1
class | near_duplicates_redpajama
bool 1
class | near_duplicates_githubcode
bool 2
classes |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
15,285,566 |
cameraconfig.c
|
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam/cameraconfig.c
|
/*******************************************************************************#
# guvcview http://guvcview.sourceforge.net #
# #
# Paulo Assis <[email protected]> #
# #
# This program is free software; you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation; either version 2 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software #
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #
# #
********************************************************************************/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <locale.h>
#include <sys/types.h>
#include <fcntl.h>
#include <assert.h>
#include <libintl.h>
#include "gviewv4l2core.h"
#include "gview.h"
#include "core_io.h"
#include "gui.h"
#include "cameraconfig.h"
#define MAXLINE 100 /*100 char lines max*/
extern int debug_level;
static config_t my_config =
{
.width = 1920,
.height = 1080,
.device_name = NULL,
.device_location = NULL,
.format = V4L2_PIX_FMT_MJPEG,
.render = "sdl",
.gui = "qt5",
.audio = "port",
.capture = "mmap",
.video_codec = "mjpg",/*yuy2,mjpg,mpeg,flv1,wmv1,mpg2,mp43,dx50,h264,hevc,vp80,vp90,theo*/
.audio_codec = "aac",
.profile_name = NULL,
.profile_path = NULL,
.video_name = NULL,
.video_path = NULL,
.photo_name = NULL,
.photo_path = NULL,
.video_sufix = 1,
.photo_sufix = 1,
.fps_num = 1,
.fps_denom = 30,
.audio_device = -1,/*will use API default in this case*/
.video_fx = 0, /*no video fx*/
.audio_fx = 0, /*no audio fx*/
.osd_mask = 0, /*REND_OSD_NONE*/
.crosshair_color=0x0000FF00, /*osd crosshair rgb color (0x00RRGGBB)*/
};
/*
* save options to config file
* args:
* filename - config file
*
* asserts:
* none
*
* returns: error code
*/
int config_save(const char *filename)
{
FILE *fp;
/*open file for write*/
if((fp = fopen(filename,"w")) == NULL)
{
fprintf(stderr, "deepin-camera: couldn't open %s for write: %s\n", filename, strerror(errno));
return -1;
}
/* use c locale - make sure floats are writen with a "." and not a "," */
setlocale(LC_NUMERIC, "C");
/*write config data*/
// fprintf(fp, "#Deepin-camera %s config file\n", VERSION);
fprintf(fp, "\n");
fprintf(fp, "#video input width\n");
fprintf(fp, "width=%i\n", my_config.width);
fprintf(fp, "#video input height\n");
fprintf(fp, "height=%i\n", my_config.height);
fprintf(fp, "#device name\n");
fprintf(fp, "device_name=%s\n",my_config.device_name);
fprintf(fp, "#device location\n");
fprintf(fp, "device_location=%s\n",my_config.device_location);
fprintf(fp, "#video input format\n");
fprintf(fp, "v4l2_format=%u\n", my_config.format);
fprintf(fp, "#video input capture method\n");
fprintf(fp, "capture=%s\n", my_config.capture);
fprintf(fp, "#audio api\n");
fprintf(fp, "audio=%s\n", my_config.audio);
fprintf(fp, "#gui api\n");
fprintf(fp, "gui=%s\n", my_config.gui);
fprintf(fp, "#render api\n");
fprintf(fp, "render=%s\n", my_config.render);
fprintf(fp, "#video codec [raw mjpg mpeg flv1 wmv1 mpg2 mp43 dx50 h264 vp80 theo]\n");
fprintf(fp, "video_codec=%s\n", my_config.video_codec);
fprintf(fp, "#audio codec [pcm mp2 mp3 aac ac3 vorb]\n");
fprintf(fp, "audio_codec=%s\n", my_config.audio_codec);
fprintf(fp, "#profile name\n");
fprintf(fp, "profile_name=%s\n", my_config.profile_name);
fprintf(fp, "#profile path\n");
fprintf(fp, "profile_path=%s\n", my_config.profile_path);
fprintf(fp, "#video name\n");
fprintf(fp, "video_name=%s\n", my_config.video_name);
fprintf(fp, "#video path\n");
fprintf(fp, "video_path=%s\n", my_config.video_path);
fprintf(fp, "#video sufix flag\n");
fprintf(fp, "video_sufix=%i\n", my_config.video_sufix);
fprintf(fp, "#photo name\n");
fprintf(fp, "photo_name=%s\n", my_config.photo_name);
fprintf(fp, "#photo path\n");
fprintf(fp, "photo_path=%s\n", my_config.photo_path);
fprintf(fp, "#photo sufix flag\n");
fprintf(fp, "photo_sufix=%i\n", my_config.photo_sufix);
fprintf(fp, "#fps numerator (def. 1)\n");
fprintf(fp, "fps_num=%i\n", my_config.fps_num);
fprintf(fp, "#fps denominator (def. 25)\n");
fprintf(fp, "fps_denom=%i\n", my_config.fps_denom);
fprintf(fp, "#audio device index (-1 - api default)\n");
fprintf(fp, "audio_device=%i\n", my_config.audio_device);
fprintf(fp, "#video fx mask \n");
fprintf(fp, "video_fx=0x%x\n", my_config.video_fx);
fprintf(fp, "#audio fx mask \n");
fprintf(fp, "audio_fx=0x%x\n", my_config.audio_fx);
fprintf(fp, "#OSD mask \n");
fprintf(fp, "osd_mask=0x%x\n", my_config.osd_mask);
fprintf(fp, "crosshair_color=0x%x\n", my_config.crosshair_color);
/* return to system locale */
setlocale(LC_NUMERIC, "");
/* flush stream buffers to filesystem */
fflush(fp);
/* close file after fsync (sync file data to disk) */
if (fsync(fileno(fp)) || fclose(fp))
{
fprintf(stderr, "deeepin_camera: error writing configuration data to file: %s\n", strerror(errno));
return -1;
}
if(debug_level > 1)
printf("deeepin_camera: saving config to %s\n", filename);
return 0;
}
/*
* load options from config file
* args:
* filename - config file
*
* asserts:
* none
*
* returns: error code
*/
int config_load(const char *filename)
{
FILE *fp;
char bufr[MAXLINE];
int line = 0;
/*open file for read*/
if((fp = fopen(filename,"r")) == NULL)
{
fprintf(stderr, "deepin-camera: couldn't open %s for read: %s\n", filename, strerror(errno));
return -1;
}
while(fgets(bufr, MAXLINE, fp) != NULL)
{
line++;
char *bufp = bufr;
/*parse config line*/
/*trim leading and trailing spaces and newline*/
trim_leading_wspaces(bufp);
trim_trailing_wspaces(bufp);
/*skip empty or commented lines */
int size = strlen(bufp);
if(size < 1 || *bufp == '#')
{
if(debug_level > 1)
printf("deepin-camera: (config) empty or commented line (%i)\n", line);
continue;
}
char *token = NULL;
char *value = NULL;
char *sp = strrchr(bufp, '=');
if(sp)
{
long size = sp - bufp;
token = strndup(bufp, (ulong)size);
trim_leading_wspaces(token);
trim_trailing_wspaces(token);
value = strdup(sp + 1);
trim_leading_wspaces(value);
trim_trailing_wspaces(value);
}
/*skip invalid lines */
if(!token || !value || strlen(token) < 1 || strlen(value) < 1)
{
fprintf(stderr, "deepin-camera: (config) skiping invalid config entry at line %i\n", line);
if(token)
free(token);
if(value)
free(value);
continue;
}
/*check tokens*/
if(strcmp(token, "width") == 0)
my_config.width = (int) strtoul(value, NULL, 10);
else if(strcmp(token, "height") == 0)
my_config.height = (int) strtoul(value, NULL, 10);
else if(strcmp(token, "device_name") == 0 && strlen(value) > 0)
{
if(my_config.device_name)
free(my_config.device_name);
my_config.device_name = strdup(value);
set_device_name(value);
}
else if(strcmp(token, "device_location") == 0 && strlen(value) > 0)
{
if(my_config.device_location)
free(my_config.device_location);
my_config.device_location = strdup(value);
set_device_location(value);
}
else if(strcmp(token, "v4l2_format") == 0)
my_config.format = (uint32_t) strtoul("V4L2_PIX_FMT_MJPEG", NULL, 10);
// else if(strcmp(token, "capture") == 0)
// strncpy(my_config.capture, value, 4);
// else if(strcmp(token, "audio") == 0)
// strncpy(my_config.audio, value, 5);
// else if(strcmp(token, "gui") == 0)
// strncpy(my_config.gui, value, 4);
// else if(strcmp(token, "render") == 0)
// strncpy(my_config.render, value, 4);
// else if(strcmp(token, "video_codec") == 0)
// strncpy(my_config.video_codec, value, 4);
// else if(strcmp(token, "audio_codec") == 0)
// strncpy(my_config.audio_codec, value, 4);
// else if(strcmp(token, "profile_name") == 0 && strlen(value) > 2)
// {
// if(my_config.profile_name)
// free(my_config.profile_name);
// my_config.profile_name = strdup(value);
// set_profile_name(value);
// }
// else if(strcmp(token, "profile_path") == 0)
// {
// if(my_config.profile_path)
// free(my_config.profile_path);
// my_config.profile_path = strdup(value);
// set_profile_path(value);
// }
else if(strcmp(token, "video_name") == 0 && strlen(value) > 2)
{
if(my_config.video_name)
free(my_config.video_name);
my_config.video_name = strdup(value);
}
else if(strcmp(token, "video_path") == 0)
{
if(my_config.video_path)
free(my_config.video_path);
my_config.video_path = strdup(value);
}
else if(strcmp(token, "photo_name") == 0 && strlen(value) > 2)
{
if(my_config.photo_name)
free(my_config.photo_name);
my_config.photo_name = strdup(value);
}
else if(strcmp(token, "photo_path") == 0)
{
if(my_config.photo_path)
free(my_config.photo_path);
my_config.photo_path = strdup(value);
}
// else if(strcmp(token, "video_sufix") == 0)
// {
// my_config.video_sufix = (int) strtoul(value, NULL, 10);
// set_video_sufix_flag(my_config.video_sufix);
// }
// else if(strcmp(token, "photo_sufix") == 0)
// {
// my_config.photo_sufix = (int) strtoul(value, NULL, 10);
// set_photo_sufix_flag(my_config.photo_sufix);
// }
// else if(strcmp(token, "fps_num") == 0)
// my_config.fps_num = (int) strtoul(value, NULL, 10);
// else if(strcmp(token, "fps_denom") == 0)
// my_config.fps_denom = (int) strtoul(value, NULL, 10);
// else if(strcmp(token, "audio_device") == 0)
// my_config.audio_device = (int) strtoul(value, NULL, 10);
// else if(strcmp(token, "video_fx") == 0)
// my_config.video_fx = (uint32_t) strtoul(value, NULL, 16);
// else if(strcmp(token, "audio_fx") == 0)
// my_config.audio_fx = (uint32_t) strtoul(value, NULL, 16);
// else if(strcmp(token, "osd_mask") == 0)
// my_config.osd_mask = (uint32_t) strtoul(value, NULL, 16);
// else if(strcmp(token, "crosshair_color") == 0)
// my_config.crosshair_color = (uint32_t) strtoul(value, NULL, 16);
// else
// fprintf(stderr, "deepin-camera: (config) skiping invalid entry at line %i ('%s', '%s')\n", line, token, value);
if(token)
free(token);
if(value)
free(value);
}
//if(errno)
//{
// fprintf(stderr, "deepin-camera: couldn't read line %i of config file: %s\n", line, strerror(errno));
// fclose(fp);
// return -1;
//}
fclose(fp);
return 0;
}
/*
* update config data with options data
* args:
* my_options - pointer to options data
*
* asserts:
* none
*
* returns: none
*/
void config_update(options_t *my_options)
{
/*check for resolution options*/
if(my_options->width > 0)
my_config.width = my_options->width;
if(my_options->height > 0)
my_config.height = my_options->height;
/*check for resolution options*/
if(my_options->fps_num > 0)
my_config.fps_num = my_options->fps_num;
if(my_options->fps_denom > 0)
my_config.fps_denom = my_options->fps_denom;
/*capture method*/
if(strlen(my_options->capture) > 3)
strncpy(my_config.capture, my_options->capture, 4);
/*render API*/
if(strlen(my_options->render) > 2)
strncpy(my_config.render, my_options->render, 4);
/*gui API*/
if(strlen(my_options->gui) > 2)
strncpy(my_config.gui, my_options->gui, 4);
/*audio API*/
if(strlen(my_options->audio) > 3)
strncpy(my_config.audio, my_options->audio, 5);
/*audio device*/
if(my_options->audio_device >= 0)
my_config.audio_device = my_options->audio_device;
/*input format*/
if(strlen(my_options->format) > 2)
{
//convert to v4l2_format
my_config.format = v4l2core_fourcc_2_v4l2_pixelformat(my_options->format);
}
/*video codec*/
if(strlen(my_options->video_codec) > 2)
strncpy(my_config.video_codec, my_options->video_codec, 4);
/*audio codec*/
if(strlen(my_options->audio_codec) > 2)
strncpy(my_config.audio_codec, my_options->audio_codec, 4);
/*profile*/
if(my_options->profile_name)
{
if(my_config.profile_name)
free(my_config.profile_name);
my_config.profile_name = strdup(my_options->profile_name);
}
if(my_options->profile_path)
{
if(my_config.profile_path)
free(my_config.profile_path);
my_config.profile_path = strdup(my_options->profile_path);
}
/*video file*/
if(my_options->video_name)
{
if(my_config.video_name)
free(my_config.video_name);
my_config.video_name = strdup(my_options->video_name);
}
if(my_options->video_path)
{
if(my_config.video_path)
free(my_config.video_path);
my_config.video_path = strdup(my_options->video_path);
}
/*photo*/
if(my_options->photo_name)
{
if(my_config.photo_name)
free(my_config.photo_name);
my_config.photo_name = strdup(my_options->photo_name);
}
if(my_options->photo_path)
{
if(my_config.photo_path)
free(my_config.photo_path);
my_config.photo_path = strdup(my_options->photo_path);
}
}
/*
* cleans internal config allocations
* args:
* none
*
* asserts:
* none
*
* returns: none
*/
void config_clean()
{
if(my_config.profile_name != NULL)
free(my_config.profile_name);
if(my_config.profile_path != NULL)
free(my_config.profile_path);
if(my_config.video_name != NULL)
free(my_config.video_name);
if(my_config.video_path != NULL)
free(my_config.video_path);
if(my_config.photo_name != NULL)
free(my_config.photo_name);
if(my_config.photo_path != NULL)
free(my_config.photo_path);
if(my_config.device_name != NULL)
{
free(my_config.device_name);
}
if(my_config.device_location != NULL)
{
free(my_config.device_location);
}
}
/*
* get the internal config data
* args:
* none
*
* asserts:
* none
*
* returns: pointer to internal config_t struct
*/
config_t *config_get()
{
return &my_config;
}
| 15,228 |
C
|
.c
| 462 | 29.623377 | 125 | 0.607339 |
linuxdeepin/dtkmultimedia
| 3 | 16 | 2 |
LGPL-3.0
|
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
15,285,567 |
camoptions.c
|
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam/camoptions.c
|
/*******************************************************************************#
# guvcview http://guvcview.sourceforge.net #
# #
# Paulo Assis <[email protected]> #
# #
# This program is free software; you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation; either version 2 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software #
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #
# #
********************************************************************************/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include "gviewv4l2core.h"
#include "gview.h"
#include "core_io.h"
#include "gui.h"
#include "camoptions.h"
#include "cameraconfig.h"
typedef struct _opt_values_t
{
char opt_short;
char opt_long[20];
int req_arg;
char opt_help_arg[20];
char opt_help[80];
} opt_values_t;
static opt_values_t opt_values[] =
{
{
.opt_short = 'h',
.opt_long = "help",
.req_arg = 0,
.opt_help_arg = "",
.opt_help = N_("Print help")
},
{
.opt_short = 'v',
.opt_long = "version",
.req_arg = 0,
.opt_help_arg = "",
.opt_help = N_("Print version"),
},
{
.opt_short = 'w',
.opt_long = "verbosity",
.req_arg = 1,
.opt_help_arg = N_("LEVEL"),
.opt_help = N_("Set Verbosity level (def: 0)")
},
{
.opt_short = 'd',
.opt_long = "device",
.req_arg = 1,
.opt_help_arg = N_("DEVICE"),
.opt_help = N_("Set device name (def: /dev/video0)"),
},
{
.opt_short = 'c',
.opt_long = "capture",
.req_arg = 1,
.opt_help_arg = N_("METHOD"),
.opt_help = N_("Set capture method [read | mmap (def)]"),
},
{
.opt_short = 'b',
.opt_long = "disable_libv4l2",
.req_arg = 0,
.opt_help_arg = "",
.opt_help = N_("disable calls to libv4l2"),
},
{
.opt_short = 'x',
.opt_long = "resolution",
.req_arg = 1,
.opt_help_arg = N_("WIDTHxHEIGHT"),
.opt_help = N_("Request resolution (e.g 640x480)")
},
{
.opt_short = 'f',
.opt_long = "format",
.req_arg = 1,
.opt_help_arg = N_("FOURCC"),
.opt_help = N_("Request format (e.g MJPG)")
},
{
.opt_short = 'F',
.opt_long = "fps",
.req_arg = 1,
.opt_help_arg = N_("FPS_NUM[/FPS_DENOM]"),
.opt_help = N_("Request fps (e.g 25 ; 7/3; ...)")
},
{
.opt_short = 'm',
.opt_long = "render_window",
.req_arg = 1,
.opt_help_arg = N_("RENDER_WINDOW_FLAGS"),
.opt_help = N_("Set render window flags (e.g none; full; max; WIDTHxHEIGHT)")
},
{
.opt_short = 'a',
.opt_long = "audio",
.req_arg = 1,
.opt_help_arg = N_("AUDIO_API"),
.opt_help = N_("Select audio API (e.g none; port; pulse)")
},
{
.opt_short = 'k',
.opt_long = "audio_device",
.req_arg = 1,
.opt_help_arg = N_("AUDIO_DEVICE"),
.opt_help = N_("Select audio device index for selected api (0..N)")
},
{
.opt_short = 'o',
.opt_long = "audio_codec",
.req_arg = 1,
.opt_help_arg = N_("CODEC"),
.opt_help = N_("Audio codec [pcm mp2 mp3 aac ac3 vorb]")
},
{
.opt_short = 'u',
.opt_long = "video_codec",
.req_arg = 1,
.opt_help_arg = N_("CODEC"),
.opt_help = N_("Video codec [raw mjpg mpeg flv1 wmv1 mpg2 mp43 dx50 h264 vp80 theo]")
},
{
.opt_short = 'p',
.opt_long = "profile",
.req_arg = 1,
.opt_help_arg = N_("FILENAME"),
.opt_help = N_("load control profile")
},
{
.opt_short = 'j',
.opt_long = "video",
.req_arg = 1,
.opt_help_arg = N_("FILENAME"),
.opt_help = N_("filename for captured video)")
},
{
.opt_short = 'i',
.opt_long = "image",
.req_arg = 1,
.opt_help_arg = N_("FILENAME"),
.opt_help = N_("filename for captured image)")
},
{
.opt_short = 'y',
.opt_long = "video_timer",
.req_arg = 1,
.opt_help_arg = N_("TIME_IN_SEC"),
.opt_help = N_("time (double) in sec. for video capture)")
},
{
.opt_short = 't',
.opt_long = "photo_timer",
.req_arg = 1,
.opt_help_arg = N_("TIME_IN_SEC"),
.opt_help = N_("time (double) in sec. between captured photos)")
},
{
.opt_short = 'n',
.opt_long = "photo_total",
.req_arg = 1,
.opt_help_arg = N_("TOTAL"),
.opt_help = N_("total number of captured photos)")
},
{
.opt_short = 'e',
.opt_long = "exit_on_term",
.req_arg = 0,
.opt_help_arg = "",
.opt_help = N_("exit app after video or image capture ends")
},
{
.opt_short = 'z',
.opt_long = "control_panel",
.req_arg = 0,
.opt_help_arg = "",
.opt_help = N_("Start in control panel mode")
},
{
.opt_short = 0,
.opt_long = "",
.req_arg = 0,
.opt_help_arg = "",
.opt_help = ""
},
};
static options_t my_options =
{
.verbosity = 0,
.device = "",
.width = 0,
.height = 0,
.control_panel = 0,
.disable_libv4l2 = 0,
.format = "MJPG",
.render = "",
.gui = "",
.audio = "",
.audio_device = -1, /*use default*/
.capture = "",
.video_codec = "",
.audio_codec = "",
.prof_filename = NULL,
.profile_name = NULL,
.profile_path = NULL,
.video_name = "",
.video_path = "",
.photo_name = "",
.photo_path = "",
.video_timer = 0,
.photo_timer = 0,
.photo_npics = 0,
.exit_on_term = 0,
.render_flag = "none",
.render_width = 0,
.render_height = 0
};
/*
* get the internal options data
* args:
* none
*
* asserts:
* none
*
* returns: pointer to internal options_t struct
*/
options_t *options_get()
{
return &my_options;
}
/*
* prints the number of command line options
* args:
* none
*
* asserts:
* none
*
* returns: last valid index of opt_values
*/
int opt_get_number()
{
int i = 0;
/*long option must always be set*/
do
{
i++;
}
while(strlen(opt_values[i].opt_long) > 0);
return i;
}
/*
* gets the max length of help string (up to end of opt_help_arg)
* args:
* none
*
* asserts:
* none
*
* returns: max lenght
*/
static int opt_get_help_max_len()
{
int i = 0;
int max_len = 0;
/*long option must always be set*/
do
{
int len = 5 + /*-c, and --*/
strlen(opt_values[i].opt_long);
if(strlen(opt_values[i].opt_help_arg) > 0)
len += strlen(opt_values[i].opt_help_arg) + 1; /*add =*/
if(len > max_len)
max_len = len;
i++;
}
while(strlen(opt_values[i].opt_long) > 0);
return max_len;
}
/*
* prints the command line help
* args:
* none
*
* asserts:
* none
*
* returns: none
*/
void opt_print_help()
{
// printf(_("Deepin-camera version %s\n\n"), VERSION);
printf(_("Usage:\n Deepin-camera [OPTIONS]\n\n"));
printf(_("OPTIONS:\n"));
int max_len = opt_get_help_max_len();
int len = 0;
int i = 0;
/*long option must always be set*/
do
{
if(opt_values[i].opt_short > 0)
{
len = 3;
printf("-%c,", opt_values[i].opt_short);
}
printf("--%s", opt_values[i].opt_long);
len += strlen(opt_values[i].opt_long) + 2;
if(strlen(opt_values[i].opt_help_arg) > 0)
{
len += strlen(opt_values[i].opt_help_arg) + 1;
printf("=%s", _(opt_values[i].opt_help_arg));
}
int spaces = max_len - len;
int j = 0;
for(j=0; j < spaces; j++)
printf(" ");
if(strlen(opt_values[i].opt_help) > 0)
printf("\t:%s\n", _(opt_values[i].opt_help));
i++;
}
while(strlen(opt_values[i].opt_long) > 0);
}
/*
* prints the version info
* args:
* none
*
* asserts:
* none
*
* returns: none
*/
void opt_print_version()
{
// printf("Deepin-camera version %s\n", VERSION);
}
/*
* parses the command line options
* args:
* argc - number of comman line args
* argv - pointer to list of command line args
*
* asserts:
* none
*
* returns: int (if > 0 app should terminate (help, version)
*/
int options_parse(int argc, char *argv[])
{
int ret = 0;
int long_index =0;
char *stopstring;
int n_options = opt_get_number();
struct option long_options[n_options + 1];
char opt_string[128] = "";
char *opt_str_ptr = opt_string;
int i =0;
for(i=0; i < n_options; i++)
{
long_options[i].name = opt_values[i].opt_long;
long_options[i].has_arg = opt_values[i].req_arg > 0 ? required_argument: no_argument;
long_options[i].flag = NULL;
long_options[i].val = opt_values[i].opt_short;
/*set opt string (be carefull we don't exceed size)*/
if(opt_str_ptr - opt_string < 128 - 3)
{
*opt_str_ptr++ = opt_values[i].opt_short;
if(opt_values[i].req_arg > 0)
*opt_str_ptr++ = ':';
}
}
long_options[n_options].name = 0;
long_options[n_options].has_arg = 0;
long_options[n_options].flag = NULL;
long_options[n_options].val= 0;
*opt_str_ptr++='\0'; /*null terminated string*/
int opt = 0;
while ((opt = getopt_long(argc, argv, opt_string,
long_options, &long_index )) != -1)
{
switch (opt)
{
case 'v' :
opt_print_version();
ret = 1;
break;
case 'w':
my_options.verbosity = atoi(optarg);
break;
case 'd':
{
int str_size = strlen(optarg);
if(str_size > 1) /*device needs at least 2 chars*/
strncpy(my_options.device, optarg, 29);
else
fprintf(stderr, "V4L2_CORE: (options) Error in device usage: -d[--device] DEVICENAME \n");
break;
}
case 'z':
{
my_options.control_panel = 1;
break;
}
case 'c':
{
int str_size = strlen(optarg);
if(str_size == 4) /*capture method*/
strncpy(my_options.capture, optarg, 4);
break;
}
case 'b':
{
my_options.disable_libv4l2 = 1;
break;
}
case 'x':
my_options.width = (int) strtoul(optarg, &stopstring, 10);
if( *stopstring != 'x')
{
fprintf(stderr, "V4L2_CORE: (options) Error in resolution usage: -x[--resolution] WIDTHxHEIGHT \n");
}
else
{
++stopstring;
my_options.height = (int) strtoul(stopstring, &stopstring, 10);
}
if(my_options.width <= 0)
my_options.width = 640;
if(my_options.height <= 0)
my_options.height = 480;
break;
case 'f':
{
int str_size = strlen(optarg);
if(str_size == 4) /*fourcc is 4 chars*/
strncpy(my_options.format, optarg, 4);
break;
}
case 'F':
/* numerator and denominator are reversed
* since fps here is actually time between frame
*/
my_options.fps_num = 1;
my_options.fps_denom = (int) strtoul(optarg, &stopstring, 10);
if( *stopstring == '/')
{
++stopstring;
my_options.fps_num = (int) strtoul(stopstring, &stopstring, 10);
}
if(my_options.fps_denom <= 0)
my_options.fps_denom = 25;
if(my_options.fps_num <= 0)
my_options.fps_num = 1;
break;
case 'r':
{
int str_size = strlen(optarg);
if(str_size <= 4) /*render is at most 4 chars*/
strncpy(my_options.render, optarg, 4);
break;
}
case 'm':
{
int str_size = strlen(optarg);
if(str_size <= 4) /*[none, full, max] is at most 4 chars*/
strncpy(my_options.render_flag, optarg, 4);
else
{
my_options.render_width = (int) strtoul(optarg, &stopstring, 10);
if(my_options.render_width <= 0 || *stopstring != 'x')
fprintf(stderr, "V4L2_CORE: (options) Error in render_window usage: -m[--render_window=] none|full|max|WIDTHxHEIGHT \n");
else
{
++stopstring;
my_options.render_height = (int) strtoul(stopstring, &stopstring, 10);
}
}
if(my_options.render_width < 0)
my_options.render_width = 0;
if(my_options.render_height < 0)
my_options.render_height = 0;
break;
}
case 'g':
{
int str_size = strlen(optarg);
if(str_size <= 4) /*gui is at maximum 4 chars*/
strncpy(my_options.gui, optarg, 4);
break;
}
case 'a':
{
/*audio api is at most 5 chars (p u l s e)*/
strncpy(my_options.audio, optarg, 5);
break;
}
case 'k':
my_options.audio_device = atoi(optarg);
break;
case 'o':
{
int str_size = strlen(optarg);
if(str_size > 2) /*audio codec*/
strncpy(my_options.audio_codec, optarg, 4);
break;
}
case 'u':
{
int str_size = strlen(optarg);
if(str_size > 2) /*video codec*/
strncpy(my_options.video_codec, optarg, 4);
break;
}
case 'p':
{
if(my_options.prof_filename != NULL)
free(my_options.prof_filename);
my_options.prof_filename = strdup(optarg);
/*get profile path and basename*/
char *basename = get_file_basename(optarg);
if(basename)
{
set_profile_name(basename);
if(my_options.profile_name != NULL)
free(my_options.profile_name);
my_options.profile_name = basename;
}
char *pathname = get_file_pathname(optarg);
if(pathname)
{
set_profile_path(pathname);
if(my_options.profile_path != NULL)
free(my_options.profile_path);
my_options.profile_path = pathname;
}
break;
}
case 'j':
{
/*get video path and basename*/
char *basename = get_file_basename(optarg);
if(basename)
{
//set_video_name(basename);
//free(basename);
if(my_options.video_name != NULL)
free(my_options.video_name);
my_options.video_name = basename;
}
char *pathname = get_file_pathname(optarg);
if(pathname)
{
//set_video_path(pathname);
//free(pathname);
if(my_options.video_path != NULL)
free(my_options.video_path);
my_options.video_path = pathname;
}
break;
}
case 'i':
{
/*get photo path and basename*/
char *basename = get_file_basename(optarg);
if(basename)
{
//set_photo_name(basename);
//free(basename);
if(my_options.photo_name != NULL)
free(my_options.photo_name);
my_options.photo_name = basename;
}
char *pathname = get_file_pathname(optarg);
if(pathname)
{
//set_photo_path(pathname);
//free(pathname);
if(my_options.photo_path != NULL)
free(my_options.photo_path);
my_options.photo_path = pathname;
}
break;
}
case 'y':
my_options.video_timer = strtod(optarg, (char **)NULL);
break;
case 't':
my_options.photo_timer = strtod(optarg, (char **)NULL);
break;
case 'n':
my_options.photo_npics = atoi(optarg);
break;
case 'e' :
my_options.exit_on_term = 1;
break;
default:
case 'h':
opt_print_help();
ret = 1;
break;
}
}
return ret;
}
/*
* cleans internal options allocations
* args:
* none
*
* asserts:
* none
*
* returns: none
*/
void options_clean()
{
if(my_options.prof_filename != NULL)
free(my_options.prof_filename);
my_options.prof_filename = NULL;
if(my_options.profile_name != NULL)
free(my_options.profile_name);
my_options.profile_name = NULL;
if(my_options.profile_path != NULL)
free(my_options.profile_path);
my_options.profile_path = NULL;
if(my_options.video_name != NULL)
free(my_options.video_name);
my_options.video_name = NULL;
if(my_options.video_path != NULL)
free(my_options.video_path);
my_options.video_path = NULL;
if(my_options.photo_name != NULL)
free(my_options.photo_name);
my_options.photo_name = NULL;
if(my_options.photo_path != NULL)
free(my_options.photo_path);
my_options.photo_path = NULL;
}
| 16,039 |
C
|
.c
| 656 | 21.091463 | 127 | 0.576218 |
linuxdeepin/dtkmultimedia
| 3 | 16 | 2 |
LGPL-3.0
|
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
15,285,568 |
camview.c
|
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam/camview.c
|
/*******************************************************************************#
# guvcview http://guvcview.sourceforge.net #
# #
# Paulo Assis <[email protected]> #
# #
# This program is free software; you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation; either version 2 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software #
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #
# #
********************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include <time.h>
#include <unistd.h>
#include <fcntl.h>
#include <linux/videodev2.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include <math.h>
/* support for internationalization - i18n */
#include <locale.h>
#include <libintl.h>
#include "gviewv4l2core.h"
#include "gviewrender.h"
#include "gviewencoder.h"
#include "gview.h"
#include "camview.h"
#include "camoptions.h"
#include "cameraconfig.h"
#include "core_io.h"
#include "gui.h"
/*flags*/
extern int debug_level;//debug
__MUTEX_TYPE capture_mutex = __STATIC_MUTEX_INIT;//初始化静态锁
__COND_TYPE capture_cond;
static int render = RENDER_SDL; /*render API*/
static int quit = 0; /*terminate flag*/
static int save_image = 0; /*save image flag*/
static int save_video = 0; /*save video flag*/
static uint64_t my_photo_timer = 0; /*timer count*/
static uint64_t my_video_timer = 0; /*timer count*/
static uint64_t my_video_begin_time = 0; /*first video frame ts*/
static int restart = 0; /*restart flag*/
static char render_caption[30]; /*render window caption*/
static uint32_t my_render_mask = REND_FX_YUV_NOFILT; /*render fx filter mask*/
static uint32_t my_audio_mask = AUDIO_FX_NONE; /*audio fx filter mask*/
/*暂停录制*/
static int capture_pause = 0;
/*暂停时刻的视频时间*/
static int64_t video_timestamp_tmp = 0;
/*音频时间引用*/
static int64_t audio_timestamp_reference = 0;
/*暂停时刻的音频时间*/
static int64_t audio_timestamp_tmp = 0;
/*音频的暂停总时间*/
static int64_t audio_pause_timestamp = 0;
static double video_time_capture = 0;
/*continues focus*/
static int do_soft_autofocus = 0;
/*single time focus (can happen during continues focus)*/
static int do_soft_focus = 0;
/*pointer to audio context data*/
static audio_context_t *my_audio_ctx = NULL;
/*pointer to v4l2 device handler*/
static v4l2_dev_t *my_vd = NULL;
static __THREAD_TYPE encoder_thread;
static int my_encoder_status = 0;
static int is_wayland = 0; //是否是wayland的窗口管理器
static uint8_t soundTakePhoto = 1;//拍照声音提示
static char status_message[80];
void set_video_time_capture(double video_time)
{
video_time_capture = video_time;
}
double get_video_time_capture()
{
return video_time_capture;
}
/*
* set pause times
* args:
* value - timestamp
*
* asserts:
* none
*
* returns: none
*/
void set_video_timestamptmp(int64_t timestamp)
{
video_timestamp_tmp = timestamp;
}
/*
* get pause times
* args:
* value: none
*
* asserts:
* none
*
* returns: pause_time
*/
int64_t get_video_timestamptmp(void)
{
return video_timestamp_tmp;
}
/*
* set capture_pause flag
* args:
* value - flag value
*
* asserts:
* none
*
* returns: none
*/
void set_capture_pause(int bvalue)
{
if(capture_pause != bvalue)
capture_pause = bvalue;
printf("capture_pause = %d\n", bvalue);
}
/*
* get capture_pause value
* args:
* none
*
* asserts:
* none
*
* returns: capture_pause
*/
int get_capture_pause()
{
return capture_pause;
}
/*
* set render flag
* args:
* value - flag value
*
* asserts:
* none
*
* returns: none
*/
void set_render_flag(int value)
{
render = value;
}
/*
* get render fx mask
* args:
* none
*
* asserts:
* none
*
* returns: render fx mask
*/
uint32_t get_render_fx_mask()
{
return my_render_mask;
}
/*
* set render fx mask
* args:
* new_mask - fx mask value
*
* asserts:
* none
*
* returns: none
*/
void set_render_fx_mask(uint32_t new_mask)
{
my_render_mask = new_mask;
/* update config */
config_t *my_config = config_get();
my_config->video_fx = my_render_mask;
}
/*
* get audio fx mask
* args:
* none
*
* asserts:
* none
*
* returns: audio fx mask
*/
uint32_t get_audio_fx_mask()
{
return my_audio_mask;
}
/*
* set audio fx mask
* args:
* new_mask - new audio fx filter mask
*
* asserts:
* none
*
* returns: none
*/
void set_audio_fx_mask(uint32_t new_mask)
{
my_audio_mask = new_mask;
/* update config */
config_t *my_config = config_get();
my_config->audio_fx = my_audio_mask;
}
/*
* set software autofocus flag
* args:
* value - flag value
*
* asserts:
* none
*
* returns: none
*/
void set_soft_autofocus(int value)
{
do_soft_autofocus = value;
}
/*
* sets the save video flag
* args:
* value - save_video flag value
*
* asserts:
* none
*
* returns: none
*/
void video_capture_save_video(int value)
{
save_video = value;
if(debug_level > 1)
printf("deepin-camera: save video flag changed to %i\n", save_video);
}
/*
* gets the save video flag
* args:
* none
*
* asserts:
* none
*
* returns: save_video flag
*/
int video_capture_get_save_video()
{
return save_video;
}
/*
* sets the save image flag
* args:
* none
*
* asserts:
* none
*
* returns: none
*/
void video_capture_save_image()
{
save_image = 1;
}
/*
* get encoder started flag
* args:
* none
*
* asserts:
* none
*
* returns: encoder started flag (1 -started; 0 -not started)
*/
int get_encoder_status()
{
return my_encoder_status;
}
/*
* stops the photo timed capture
* args:
* none
*
* asserts:
* none
*
* returns: none
*/
void stop_photo_timer()
{
my_photo_timer = 0;
//gui_set_image_capture_button_label(_("Cap. Image (I)"));
}
/*
* checks if photo timed capture is on
* args:
* none
*
* asserts:
* none
*
* returns: 1 if on; 0 if off
*/
int check_photo_timer()
{
return ( (my_photo_timer > 0) ? 1 : 0 );
}
/*
* reset video timer
* args:
* none
*
* asserts:
* none
*
* returns: none
*/
void reset_video_timer()
{
my_video_timer = 0;
my_video_begin_time = 0;
}
/*
* set video begin timer
* args:
* begin_time
*
* asserts:
* none
*
* returns: none
*/
void set_myvideo_begin_timer(ulong begin_time)
{
my_video_begin_time = begin_time;
}
/*
* get video begin timer
* args:
* none
*
* asserts:
* none
*
* returns: video begin timer
*/
ulong get_myvideo_bebin_timer(void)
{
return my_video_begin_time;
}
/*
* set video timer
* args:
* timer
*
* asserts:
* none
*
* returns: none
*/
void set_video_timer(ulong timer)
{
my_video_timer = NSEC_PER_SEC * timer;
}
/*
* stops the video timed capture
* args:
* none
*
* asserts:
* none
*
* returns: none
*/
static void stop_video_timer()
{
/*
* if we are saving video stop it
* this also calls reset_video_timer
*/
if(video_capture_get_save_video())
{
stop_encoder_thread();
reset_video_timer();
}
/*make sure the timer is reset*/
reset_video_timer();
}
/*
* checks if video timed capture is on
* args:
* none
*
* asserts:
* none
*
* returns: 1 if on; 0 if off
*/
int check_video_timer()
{
return ( (my_video_timer > 0) ? 1 : 0 );
}
/*
* set software focus flag
* args:
* value - flag value
*
* asserts:
* none
*
* returns: none
*/
void set_soft_focus(int value)
{
v4l2core_soft_autofocus_set_focus();
do_soft_focus = value;
}
/*
* request format update
* args:
* none
*
* asserts:
* none
*
* returns: none
*/
void request_format_update(int bstatus)
{
restart = bstatus;
}
int get_resolution_status()
{
return restart;
}
/*
* create a v4l2 device handler
* args:
* device - device name
*
* asserts:
* none
*
* returns: pointer to v4l2 device handler (or null on error)
*/
v4l2_dev_t *get_v4l2_dev(const char *device)
{
my_vd = v4l2core_init_dev(device);
return my_vd;
}
/*
* close the v4l2 device handler
* args:
* none
*
* asserts:
* none
*
* returns: none
*/
void close_v4l2_device_handler()
{
/*closes the video device*/
v4l2core_close_dev(my_vd);
my_vd = NULL;
}
/*
* get the v4l2 device handler
* args:
* none
*
* asserts:
* none
*
* returns: pointer to v4l2 device handler
*/
v4l2_dev_t *get_v4l2_device_handler()
{
return my_vd;
}
/*
* create an audio context
* args:
* api - audio api
* device - api device index (-1 use default)
*
* asserts:
* none
*
* returns: pointer to audio context data
*/
audio_context_t *create_audio_context(int api, int device)
{
close_audio_context();
my_audio_ctx = audio_init(api, device);
if(my_audio_ctx == NULL)
fprintf(stderr, "deepin-camera: couldn't allocate audio context\n");
return my_audio_ctx;
}
/*
* get audio context
* args:
* none
*
* asserts:
* none
*
* returns: pointer to audio context data (or NULL if no audio)
*/
audio_context_t *get_audio_context()
{
if(!my_audio_ctx)
return NULL;
/*force a valid number of channels*/
if(audio_get_channels(my_audio_ctx) > 2)
audio_set_channels(my_audio_ctx, 2);
return my_audio_ctx;
}
/*
* close the audio context
* args:
* none
*
* asserts:
* none
*
* returns: none
*/
void close_audio_context()
{
if(my_audio_ctx != NULL)
audio_close(my_audio_ctx);
my_audio_ctx = NULL;
}
/*
* audio processing loop (should run in a separate thread)
* args:
* data - pointer to user data
*
* asserts:
* none
*
* returns: pointer to return code
*/
static void *audio_processing_loop(void *data)
{
encoder_context_t *encoder_ctx = (encoder_context_t *) data;
if(debug_level > 1)
printf("deepin-camera: audio thread (tid: %u)\n",
(unsigned int) syscall (SYS_gettid));
audio_context_t *audio_ctx = get_audio_context();
if(!audio_ctx)
{
fprintf(stderr, "deepin-camera: no audio context: skiping audio processing\n");
return ((void *) -1);
}
audio_buff_t *audio_buff = NULL;
/*start audio capture*/
int frame_size = encoder_get_audio_frame_size(encoder_ctx);
//获取每个音频帧里面的样本数
//if(frame_size < 1024)
// frame_size = 1024;
//初始化音频样本获取缓存大小
audio_set_cap_buffer_size(audio_ctx,
frame_size * audio_get_channels(audio_ctx));
audio_start(audio_ctx);
/*
* alloc the buffer after audio_start
* otherwise capture_buff_size may not
* be correct
* allocated data is big enough for float samples (32 bit)
* although it may contain int16 samples (16 bit)
*/
audio_buff = audio_get_buffer(audio_ctx);
int sample_type = encoder_get_audio_sample_fmt(encoder_ctx);
uint32_t osd_mask = render_get_osd_mask();
/*enable vu meter OSD display*/
if(audio_get_channels(audio_ctx) > 1)
osd_mask |= REND_OSD_VUMETER_STEREO;
else
osd_mask |= REND_OSD_VUMETER_MONO;
render_set_osd_mask(osd_mask);
while(video_capture_get_save_video())
{
if(get_capture_pause())
{
int ret = audio_get_next_buffer(audio_ctx, audio_buff, sample_type, my_audio_mask);
if(ret == 0)
{
audio_pause_timestamp = audio_buff->timestamp - audio_timestamp_tmp;
}
continue;
}
int ret = audio_get_next_buffer(audio_ctx, audio_buff,
sample_type, my_audio_mask);
audio_timestamp_tmp = audio_buff->timestamp;
if(audio_pause_timestamp != 0) {
audio_timestamp_reference += audio_pause_timestamp;
audio_pause_timestamp = 0;
}
if(ret > 0) {
/*
* no buffers to process
* sleep a couple of milisec
*/
struct timespec req = {
.tv_sec = 0,
.tv_nsec = 1000000};/*nanosec*/
nanosleep(&req, NULL);
} else if(ret == 0) {
encoder_ctx->enc_audio_ctx->pts = audio_buff->timestamp - audio_timestamp_reference;
/*OSD vu meter level*/
render_set_vu_level(audio_buff->level_meter);
encoder_process_audio_buffer(encoder_ctx, audio_buff->data);
}
}
/*flush any delayed audio frames*/
encoder_flush_audio_buffer(encoder_ctx);
audio_timestamp_tmp = 0;
audio_pause_timestamp = 0;
audio_timestamp_reference = 0;
/*reset vu meter*/
audio_buff->level_meter[0] = 0;
audio_buff->level_meter[1] = 0;
render_set_vu_level(audio_buff->level_meter);
/*disable OSD vumeter*/
osd_mask &= ~REND_OSD_VUMETER_STEREO;
osd_mask &= ~REND_OSD_VUMETER_MONO;
render_set_osd_mask(osd_mask);
audio_stop(audio_ctx);
audio_delete_buffer(audio_buff);
return ((void *) 0);
}
/*
* encoder loop (should run in a separate thread)
* args:
* data - pointer to user data
*
* asserts:
* none
*
* returns: pointer to return code
*/
static void *encoder_loop(__attribute__((unused))void *data)
{
my_encoder_status = 1;
if(debug_level > 1)
printf("deepin-camera: encoder thread (tid: %u)\n",
(unsigned int) syscall (SYS_gettid));
/*get the audio context*/
audio_context_t *audio_ctx = get_audio_context();
__THREAD_TYPE encoder_audio_thread;
int channels = 0;
int samprate = 0;
if(audio_ctx)
{
channels = audio_get_channels(audio_ctx);//
samprate = audio_get_samprate(audio_ctx);//采样率
}
if(debug_level > 0)
printf("deepin-camera: audio [channels= %i; samprate= %i] \n",
channels, samprate);
/*create the encoder context*/
encoder_context_t *encoder_ctx = encoder_init(
v4l2core_get_requested_frame_format(my_vd),
get_video_codec_ind(),
get_audio_codec_ind(),
get_video_muxer(),
v4l2core_get_frame_width(my_vd),
v4l2core_get_frame_height(my_vd),
v4l2core_get_fps_num(my_vd),
v4l2core_get_fps_denom(my_vd),
channels,
samprate);
/*store external SPS and PPS data if needed*/
if(encoder_ctx->video_codec_ind == 0 && /*raw - direct input*/
v4l2core_get_requested_frame_format(my_vd) == V4L2_PIX_FMT_H264)
{
/*request a IDR (key) frame*/
v4l2core_h264_request_idr(my_vd);
if(debug_level > 0)
printf("deepin-camera: storing external pps and sps data in encoder context\n");
encoder_ctx->h264_pps_size = v4l2core_get_h264_pps_size(my_vd);
if(encoder_ctx->h264_pps_size > 0)
{
encoder_ctx->h264_pps = calloc(encoder_ctx->h264_pps_size, sizeof(uint8_t));
if(encoder_ctx->h264_pps == NULL)
{
fprintf(stderr,"deepin-camera: FATAL memory allocation failure (encoder_loop): %s\n", strerror(errno));
exit(-1);
}
memcpy(encoder_ctx->h264_pps, v4l2core_get_h264_pps(my_vd), encoder_ctx->h264_pps_size);
}
encoder_ctx->h264_sps_size = v4l2core_get_h264_sps_size(my_vd);
if(encoder_ctx->h264_sps_size > 0)
{
encoder_ctx->h264_sps = calloc(encoder_ctx->h264_sps_size, sizeof(uint8_t));
if(encoder_ctx->h264_sps == NULL)
{
fprintf(stderr,"deepin-camera: FATAL memory allocation failure (encoder_loop): %s\n", strerror(errno));
exit(-1);
}
memcpy(encoder_ctx->h264_sps, v4l2core_get_h264_sps(my_vd), encoder_ctx->h264_sps_size);
}
}
uint32_t current_framerate = 0;
if(v4l2core_get_requested_frame_format(my_vd) == V4L2_PIX_FMT_H264)
{
/* store framerate since it may change due to scheduler*/
current_framerate = v4l2core_get_h264_frame_rate_config(my_vd);
}
char *video_filename = NULL;
/*get_video_[name|path] always return a non NULL value*/
char *name = strdup(get_video_name());
char *path = strdup(get_video_path());
// if(get_video_sufix_flag())
// {
// char *new_name = add_file_suffix(path, name);
// free(name); /*free old name*/
// name = new_name; /*replace with suffixed name*/
// }
int pathsize = strlen(path);
if(path[pathsize - 1] != '/')
video_filename = smart_cat(path, '/', name);
else
video_filename = smart_cat(path, 0, name);
snprintf(status_message, 79, _("saving video to %s"), video_filename);
//gui_status_message(status_message);
/*muxer initialization*/
encoder_muxer_init(encoder_ctx, video_filename);
/*start video capture*/
video_capture_save_video(1);
// int treshold = 358400; /*100 Mbytes*/
// int64_t last_check_pts = 0; /*last pts when disk supervisor called*/
/*start audio processing thread*/
if(encoder_ctx->enc_audio_ctx != NULL && audio_get_channels(audio_ctx) > 0)
{
if(debug_level > 1)
printf("deepin-camera: starting encoder audio thread\n");
int ret = __THREAD_CREATE(&encoder_audio_thread, audio_processing_loop, (void *) encoder_ctx);
if(ret)
fprintf(stderr, "deepin-camera: encoder audio thread creation failed (%i)\n", ret);
else if(debug_level > 2)
printf("deepin-camera: created audio encoder thread with tid: %u\n",
(unsigned int) encoder_audio_thread);
}
while(video_capture_get_save_video())
{
/*process the video buffer*/
if(encoder_process_next_video_buffer(encoder_ctx) > 0)
{
/*
* no buffers to process
* sleep a couple of milisec
*/
struct timespec req = {
.tv_sec = 0,
.tv_nsec = 1000000};/*nanosec*/
nanosleep(&req, NULL);
}
/*disk supervisor*/
// if(encoder_ctx->enc_video_ctx->pts - last_check_pts > 2 * NSEC_PER_SEC)
// {
// last_check_pts = encoder_ctx->enc_video_ctx->pts;
// if(!encoder_disk_supervisor(treshold, path))
// {
// /*stop capture*/
// if((save_image || save_video) == 1)
// {
// save_image = 0;
// save_video = 0;
// }
// }
// }
}
if(debug_level > 1)
printf("deepin-camera: video capture terminated - flushing video buffers\n");
/*flush the video buffer*/
encoder_flush_video_buffer(encoder_ctx);
if(debug_level > 1)
printf("deepin-camera: flushing video buffers - done\n");
/*make sure the audio processing thread has stopped*/
if(encoder_ctx->enc_audio_ctx != NULL && audio_get_channels(audio_ctx) > 0)
{
if(debug_level > 1)
printf("deepin-camera: join encoder audio thread\n");
__THREAD_JOIN(encoder_audio_thread);
}
/*close the muxer*/
encoder_muxer_close(encoder_ctx);
/*close the encoder context (clean up)*/
encoder_close(encoder_ctx);
if(my_vd){
if(v4l2core_get_requested_frame_format(my_vd) == V4L2_PIX_FMT_H264)
{
/* restore framerate */
v4l2core_set_h264_frame_rate_config(my_vd, current_framerate);
}
}
/*clean strings*/
free(video_filename);
free(path);
free(name);
my_encoder_status = 0;
return ((void *) 0);
}
/*
* create a v4l2 device handler
* args:
* device - device name
*
* asserts:
* none
*
* returns: pointer to v4l2 device handler (or null on error)
*/
v4l2_dev_t *create_v4l2_device_handler(const char *device)
{
// cheese_print_log("create_v4l2_device_handler\n");
my_vd = v4l2core_init_dev(device);
return my_vd;
}
/*
* capture loop (should run in a separate thread)
* args:
* data - pointer to user data (options data)
*
* asserts:
* none
*
* returns: pointer to return code
*/
void *capture_loop(void *data)
{
__LOCK_MUTEX(&capture_mutex);
capture_loop_data_t *cl_data = (capture_loop_data_t *) data;
options_t *my_options = (options_t *) cl_data->options;
config_t *my_config = (config_t *) cl_data->config;
uint64_t my_last_photo_time = 0; /*timer count*/
int my_photo_npics = 0;/*no npics*/
/*reset quit flag*/
quit = 0;
if(debug_level > 1)
printf("deepin-camera: capture thread (tid: %u)\n",
(unsigned int) syscall (SYS_gettid));
int ret = 0;
int render_flags = 0;
/*render window flag =>
default (none) | FULLSCREEN (full) | MAXIMIZED (max)*/
if (strcasecmp(my_options->render_flag, "full") == 0)
render_flags = 1;
else if (strcasecmp(my_options->render_flag, "max") == 0)
render_flags = 2;
render_set_verbosity(debug_level);
render_set_crosshair_color(my_config->crosshair_color);
//渲染初始化
if(render_init(
render,
v4l2core_get_frame_width(my_vd),
v4l2core_get_frame_height(my_vd),
render_flags,
my_options->render_width,
my_options->render_height) < 0)
render = RENDER_NONE;
/*add a video capture timer*/
if(my_options->video_timer > 0)
{
my_video_timer = NSEC_PER_SEC * my_options->video_timer;
my_video_begin_time = v4l2core_time_get_timestamp(); /*timer count*/
/*if are not saving video start it*/
if(!get_encoder_status())
start_encoder_thread();
}
/*add a photo capture timer*/
if(my_options->photo_timer > 0)
{
my_photo_timer = NSEC_PER_SEC * my_options->photo_timer;
my_last_photo_time = v4l2core_time_get_timestamp(my_vd); /*timer count*/
}
if(my_options->photo_npics > 0)
my_photo_npics = my_options->photo_npics;
v4l2core_start_stream(my_vd);
v4l2_frame_buff_t *frame = NULL; //pointer to frame buffer
__COND_SIGNAL(&capture_cond);
__UNLOCK_MUTEX(&capture_mutex);
while(!quit)
{
if(restart)
{
int current_width = v4l2core_get_frame_width(my_vd);
int current_height = v4l2core_get_frame_height(my_vd);
restart = 0; /*reset*/
v4l2core_stop_stream(my_vd);
v4l2core_clean_buffers(my_vd);
/*try new format (values prepared by the request callback)*/
ret = v4l2core_update_current_format(my_vd);
/*try to set the video stream format on the device*/
if(ret != E_OK)
{
fprintf(stderr, "deepin-camera: could not set the defined stream format\n");
fprintf(stderr, "deepin-camera: trying first listed stream format\n");
v4l2core_prepare_valid_format(my_vd);
v4l2core_prepare_valid_resolution(my_vd);
ret = v4l2core_update_current_format(my_vd);
if(ret != E_OK)
{
fprintf(stderr, "deepin-camera: also could not set the first listed stream format\n");
//gui_error("Deepin-camera error", "could not start a video stream in the device", 1);
return ((void *) -1);
}
}
if((current_width != v4l2core_get_frame_width(my_vd)) ||
current_height != v4l2core_get_frame_height(my_vd))
{
if(debug_level > 1)
printf("deepin-camera: resolution changed, reseting render\n");
/*close render*/
render_close();
/*restart the render with new format*/
if(render_init(
render,
v4l2core_get_frame_width(my_vd),
v4l2core_get_frame_height(my_vd),
render_flags,
my_options->render_width,
my_options->render_height) < 0)
render = RENDER_NONE;
}
if(debug_level > 0)
printf("deepin-camera: reset to pixelformat=%x width=%i and height=%i\n",
v4l2core_get_requested_frame_format(my_vd),
v4l2core_get_frame_width(my_vd),
v4l2core_get_frame_height(my_vd));
v4l2core_start_stream(my_vd);
}
/*get the frame from v4l2 core*/
frame = v4l2core_get_decoded_frame(my_vd);
if( frame != NULL)
{
/*run software autofocus (must be called after frame was grabbed and decoded)*/
if(do_soft_autofocus || do_soft_focus)
do_soft_focus = v4l2core_soft_autofocus_run(my_vd, frame);
/* apply fx effects to the frame
* do it before saving the frame
* (we want to store the effects)
*/
render_frame_fx(frame->yuv_frame, my_render_mask);
/*check the timers*/
if(check_photo_timer())
{
if((frame->timestamp - my_last_photo_time) > my_photo_timer)
{
save_image = 1;
my_last_photo_time = frame->timestamp;
if(my_options->photo_npics > 0)
{
if(my_photo_npics > 0)
my_photo_npics--;
else
{
save_image = 0;
stop_photo_timer(); /*close timer*/
if(!check_video_timer() && my_options->exit_on_term > 0)
quit = 1; /*close app*/
}
}
}
}
if(check_video_timer())
{
if((frame->timestamp - my_video_begin_time) > my_video_timer)
{
stop_video_timer();
if(!check_photo_timer() && my_options->exit_on_term > 0)
quit = 1; /*close app*/
}
}
/*save the frame (photo)*/
if(save_image)
{
char *img_filename = NULL;
/*get_photo_[name|path] always return a non NULL value*/
char *name = strdup(get_photo_name());
char *path = strdup(get_photo_path());
if(get_photo_sufix_flag())
{
char *new_name = add_file_suffix(path, name);
free(name); /*free old name*/
name = new_name; /*replace with suffixed name*/
}
int pathsize = strlen(path);
if(path[pathsize - 1] != '/')
img_filename = smart_cat(path, '/', name);
else
img_filename = smart_cat(path, 0, name);
//if(debug_level > 1)
// printf("deepin-camera: saving image to %s\n", img_filename);
snprintf(status_message, 79, _("saving image to %s"), img_filename);
//gui_status_message(status_message);
v4l2core_save_image(frame, img_filename, get_photo_format());
free(path);
free(name);
free(img_filename);
save_image = 0; /*reset*/
}
/*save the frame (video)*/
if(video_capture_get_save_video())
{
int size = (frame->width * frame->height * 3) / 2;
uint8_t *input_frame = frame->yuv_frame;
/*
* TODO: check codec_id, format and frame flags
* (we may want to store a compressed format
*/
if(get_video_codec_ind() == 0) //raw frame
{
switch(v4l2core_get_requested_frame_format(my_vd))
{
case V4L2_PIX_FMT_H264:
input_frame = frame->h264_frame;
size = (int) frame->h264_frame_size;
break;
default:
input_frame = frame->raw_frame;
size = (int) frame->raw_frame_size;
break;
}
}
/*add the frame to the encoder buffer*/
encoder_add_video_frame(input_frame, size, frame->timestamp, frame->isKeyframe);
/*
* exponencial scheduler
* with 50% threshold (milisec)
* and max value of 250 ms (4 fps)
*/
double time_sched = encoder_buff_scheduler(ENCODER_SCHED_LIN, 0.5, 250);
if(time_sched > 0)
{
switch(v4l2core_get_requested_frame_format(my_vd))
{
case V4L2_PIX_FMT_H264:
{
uint32_t framerate = lround(time_sched * 1E6); /*nanosec*/
v4l2core_set_h264_frame_rate_config(my_vd, framerate);
break;
}
default:
{
struct timespec req = {
.tv_sec = 0,
.tv_nsec = (uint32_t) time_sched * 1E6};/*nanosec*/
nanosleep(&req, NULL);
break;
}
}
}
}
/* render the osd
* must be done after saving the frame
* (we don't want to record the osd effects)
*/
render_frame_osd(frame->yuv_frame);
/* finally render the frame */
snprintf(render_caption, 29, "Deepin-camera (%2.2f fps)",
v4l2core_get_realfps(my_vd));
render_set_caption(render_caption);
render_frame(frame->yuv_frame);
/*we are done with the frame buffer release it*/
v4l2core_release_frame(my_vd, frame);
}
}
v4l2core_stop_stream(my_vd);
/*if we are still saving video then stop it*/
if(video_capture_get_save_video())
stop_encoder_thread();
render_close();
return ((void *) 0);
}
/*
* start the encoder thread
* args:
* data - pointer to user data
*
* asserts:
* none
*
* returns: error code
*/
int start_encoder_thread(void *data)
{
int ret = __THREAD_CREATE(&encoder_thread, encoder_loop, data);
if(ret)
fprintf(stderr, "deepin-camera: encoder thread creation failed (%i)\n", ret);
else if(debug_level > 2)
printf("deepin-camera: created encoder thread with tid: %u\n",
(unsigned int) encoder_thread);
return ret;
}
/*
* stop the encoder thread
* args:
* none
*
* asserts:
* none
*
* returns: error code
*/
int stop_encoder_thread()
{
video_capture_save_video(0);
if(0 != (int)(get_video_time_capture()))
set_video_time_capture(0);
//usleep(2000);
__THREAD_JOIN(encoder_thread);
if(debug_level > 1)
printf("deepin-camera: encoder thread terminated and joined\n");
return 0;
}
void set_wayland_status(int status)
{
is_wayland = status;
}
int get_wayland_status()
{
return is_wayland;
}
void set_takeing_photo_sound(uint8_t status)
{
soundTakePhoto = status;
}
int get_sound_of_takeing_photo()
{
return soundTakePhoto;
}
| 33,078 |
C
|
.c
| 1,154 | 22.231369 | 119 | 0.562762 |
linuxdeepin/dtkmultimedia
| 3 | 16 | 2 |
LGPL-3.0
|
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
15,285,615 |
dtkmultimedia.h
|
linuxdeepin_dtkmultimedia/include/dtkmultimediawidgets/dtkmultimedia.h
|
// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: LGPL-3.0-or-later
#ifndef DMULTIMEDIA_NAMESPACE_H
#define DMULTIMEDIA_NAMESPACE_H
#define DMULTIMEDIA_NAMESPACE Dtk::Multimedia
#define DMULTIMEDIA_USE_NAMESPACE using namespace DMULTIMEDIA_NAMESPACE;
#define DMULTIMEDIA_BEGIN_NAMESPACE namespace Dtk { namespace Multimedia {
#define DMULTIMEDIA_END_NAMESPACE }}
#endif
| 425 |
C
|
.h
| 10 | 41.3 | 74 | 0.830508 |
linuxdeepin/dtkmultimedia
| 3 | 16 | 2 |
LGPL-3.0
|
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
15,285,681 |
config.h
|
linuxdeepin_dtkmultimedia/src/multimediawidgets/common/utils/config.h
|
#ifndef __CONFIG_H__
#define __CONFIG_H__
/* configured by cmake, do not edit */
#define DMR_VERSION "0"
#define VERSION "0"
#define RADIUS 8
#define RADIUS_MV 18
#endif /* __CONFIG_H__ */
| 192 |
C
|
.h
| 8 | 22.625 | 38 | 0.685083 |
linuxdeepin/dtkmultimedia
| 3 | 16 | 2 |
LGPL-3.0
|
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
15,285,728 |
file_io.h
|
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam_encoder/file_io.h
|
/*******************************************************************************#
# guvcview http://guvcview.sourceforge.net #
# #
# Paulo Assis <[email protected]> #
# #
# This program is free software; you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation; either version 2 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software #
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #
# #
********************************************************************************/
#ifndef FILE_IO_H
#define FILE_IO_H
#include <inttypes.h>
#include <sys/types.h>
#include <stdio.h>
#include "cameraconfig.h"
#define IO_BUFFER_SIZE 32768
typedef struct _io_writer_t {
FILE *fp; /* file pointer */
uint8_t *buffer; /* Start of the buffer. */
int buffer_size; /* Maximum buffer size */
uint8_t *buf_ptr; /* Current position in the buffer */
uint8_t *buf_end; /* End of the buffer. */
int64_t size; //file size (end of file position)
int64_t position; //file pointer position (updates on buffer flush)
} io_writer_t;
/*
* create a new writer:
* args:
* filename - file for write to (if NULL mem only writer)
* max_size - mem buffer size (if 0 use default)
*
* asserts:
* none
*
* returns: pointer to io_writer
*/
io_writer_t *io_create_writer(const char *filename, int max_size);
/*
* destroy the writer (clean up)
* args:
* writer - pointer to io_writer
*
* asserts:
* writer is not null
*
* returns: none
*/
void io_destroy_writer(io_writer_t *writer);
/*
* flush the writer buffer to disk
* args:
* writer - pointer to io_writer
*
* asserts:
* writer is not null
*
* returns: current offset
*/
int64_t io_flush_buffer(io_writer_t *writer);
/*
* move the writer pointer to position
* args:
* writer - pointer to io_writer
* position - new position offset
*
* asserts:
* writer is not null
*
* returns: error code
*/
int io_seek(io_writer_t *writer, int64_t position);
/*
* move file pointer by offset
* args:
* writer - pointer to io_writer
* offset - offset value to skip
*
* asserts:
* writer is not null
*
* returns: error code
*/
int io_skip(io_writer_t *writer, int offset);
/*
* get writer offset (current position)
* args:
* writer - pointer to io_writer
*
* asserts:
* writer is not null
*
* returns: current writer position offset
*/
int64_t io_get_offset(io_writer_t *writer);
/*
* write 1 octet
* args:
* writer - pointer to io_writer
* b - octect to write
*
* asserts:
* writer is not null
*
* returns: none
*/
void io_write_w8(io_writer_t *writer, uint8_t b);
/*
* write a buffer of size
* args:
* writer - pointer to io_writer
* buf - data buffer to write
* size - size of buffer
*
* asserts:
* writer is not null
*
* returns: none
*/
void io_write_buf(io_writer_t *writer, uint8_t *buf, int size);
/*
* write 2 octets (little endian)
* args:
* writer - pointer to io_writer
* val - value to write
*
* asserts:
* writer is not null
*
* returns: none
*/
void io_write_wl16(io_writer_t *writer, uint16_t val);
/*
* write 2 octets (bid endian)
* args:
* writer - pointer to io_writer
* val - value to write
*
* asserts:
* writer is not null
*
* returns: none
*/
void io_write_wb16(io_writer_t *writer, uint16_t val);
/* write 3 octets (little endian)
* args:
* writer - pointer to io_writer
* val - value to write
*
* asserts:
* writer is not null
*
* returns: none
*/
//void io_write_wl24(io_writer_t *writer, uint32_t val);
/*
* write 3 octets (bid endian)
* args:
* writer - pointer to io_writer
* val - value to write
*
* asserts:
* writer is not null
*
* returns: none
*/
//void io_write_wb24(io_writer_t *writer, uint32_t val);
/*
* write 4 octets (little endian)
* args:
* writer - pointer to io_writer
* val - value to write
*
* asserts:
* writer is not null
*
* returns: none
*/
void io_write_wl32(io_writer_t *writer, uint32_t val);
/*
* write 4 octets (bid endian)
* args:
* writer - pointer to io_writer
* val - value to write
*
* asserts:
* writer is not null
*
* returns: none
*/
void io_write_wb32(io_writer_t *writer, uint32_t val);
/*
* write 8 octets (little endian)
* args:
* writer - pointer to io_writer
* val - value to write
*
* asserts:
* writer is not null
*
* returns: none
*/
void io_write_wl64(io_writer_t *writer, uint64_t val);
/*
* write 4 octets (bid endian)
* args:
* writer - pointer to io_writer
* val - value to write
*
* asserts:
* writer is not null
*
* returns: none
*/
void io_write_wb64(io_writer_t *writer, uint64_t val);
/*
* write 4cc code
* args:
* writer - pointer to io_writer
* str - 4 char string with 4cc code
*
* asserts:
* writer is not null
*
* returns: none
*/
void io_write_4cc(io_writer_t *writer, const char *str);
/*
* write a string (null terminated)
* args:
* writer - pointer to io_writer
* str - 4 char string with 4cc code
*
* asserts:
* writer is not null
*
* returns: the size writen
*/
//int io_write_str(io_writer_t * writer, const char *str);
#if BIGENDIAN
#define io_write_w16 io_write_wb16
#define io_write_w24 io_write_wb24
#define io_write_w32 io_write_wb32
#define io_write_w64 io_write_wb64
#else
#define io_write_w16 io_write_wl16
#define io_write_w24 io_write_wl24
#define io_write_w32 io_write_wl32
#define io_write_w64 io_write_wl64
#endif
#endif
| 6,642 |
C
|
.h
| 261 | 23.555556 | 81 | 0.591689 |
linuxdeepin/dtkmultimedia
| 3 | 16 | 2 |
LGPL-3.0
|
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
15,285,738 |
audio_portaudio.h
|
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam_audio/audio_portaudio.h
|
/*******************************************************************************#
# guvcview http://guvcview.sourceforge.net #
# #
# Paulo Assis <[email protected]> #
# Nobuhiro Iwamatsu <[email protected]> #
# Add UYVY color support(Macbook iSight) #
# Flemming Frandsen <[email protected]> #
# Add VU meter OSD #
# #
# This program is free software; you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation; either version 2 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software #
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #
# #
********************************************************************************/
#ifndef GVIEWAUDIO_PORTAUDIO_H
#define GVIEWAUDIO_PORTAUDIO_H
/*
* init portaudio api
* args:
* audio_ctx - pointer to audio context data
*
* asserts:
* audio_ctx is not null
*
* returns: error code (0 = E_OK)
*/
int audio_init_portaudio(audio_context_t *audio_ctx);
/*
* set audio device
* args:
* audio_ctx - pointer to audio context data
* index - device index to set
*
* asserts:
* audio_ctx is not null
*
* returns: none
*/
void audio_set_portaudio_device(audio_context_t *audio_ctx, int index);
/*
* start portaudio stream capture
* args:
* audio_ctx - pointer to audio context data
*
* asserts:
* audio_ctx is not null
*
* returns: error code
*/
int audio_start_portaudio(audio_context_t *audio_ctx);
/*
* stop portaudio stream capture
* args:
* audio_ctx - pointer to audio context data
*
* asserts:
* audio_ctx is not null
*
* returns: error code
*/
int audio_stop_portaudio(audio_context_t *audio_ctx);
/*
* close and clean audio context for portaudio api
* args:
* audio_ctx - pointer to audio context data
*
* asserts:
* none
*
* returns: none
*/
void audio_close_portaudio(audio_context_t *audio_ctx);
void set_audio_codec_ind(int index);
#endif
| 3,204 |
C
|
.h
| 84 | 36.511905 | 81 | 0.490845 |
linuxdeepin/dtkmultimedia
| 3 | 16 | 2 |
LGPL-3.0
|
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
15,285,746 |
gui.h
|
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam_v4l2core/gui.h
|
/*******************************************************************************#
# guvcview http://guvcview.sourceforge.net #
# #
# Paulo Assis <[email protected]> #
# Nobuhiro Iwamatsu <[email protected]> #
# Add UYVY color support(Macbook iSight) #
# Flemming Frandsen <[email protected]> #
# Add VU meter OSD #
# #
# This program is free software; you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation; either version 2 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software #
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #
# #
********************************************************************************/
#ifndef GUI_H
#define GUI_H
#include "gviewv4l2core.h"
#define DEF_ACTION_IMAGE (0)
#define DEF_ACTION_VIDEO (1)
/*
* gets the current video codec index
* args:
* none
*
* asserts:
* none
*
* returns: current codec index
*/
int get_video_codec_ind();
/*
* sets the current video codec index
* args:
* index - codec index
*
* asserts:
* none
*
* returns: none
*/
void set_video_codec_ind(int index);
/*
* gets the current audio codec index
* args:
* none
*
* asserts:
* none
*
* returns: current codec index
*/
int get_audio_codec_ind();
/*
* sets the current audio codec index
* args:
* index - codec index
*
* asserts:
* none
*
* returns: none
*/
void set_audio_codec_ind(int index);
/*
* gets the current fps numerator
* args:
* none
*
* asserts:
* none
*
* returns: current fps numerator
*/
//int gui_get_fps_num();
/*
* gets the current fps denominator
* args:
* none
*
* asserts:
* none
*
* returns: current fps denominator
*/
//int gui_get_fps_denom();
/*
* stores the fps
* args:
* fps - array with fps numerator and denominator
*
* asserts:
* none
*
* returns: none
*/
void gui_set_fps(int fps[2]);
/*
* gets the control profile file name
* args:
* none
*
* asserts:
* none
*
* returns: control profile file name
*/
char *get_profile_name();
/*
* gets the control profile path (to dir)
* args:
* none
*
* asserts:
* none
*
* returns: control profile file name
*/
char *get_profile_path();
/*
* gets video sufix flag
* args:
* none
*
* asserts:
* none
*
* returns: video sufix flag
*/
int get_video_sufix_flag();
/*
* gets video muxer
* args:
* none
*
* asserts:
* none
*
* returns: video muxer
*/
int get_video_muxer();
/*
* sets video muxer
* args:
* muxer - video muxer (ENCODER_MUX_[MKV|WEBM|AVI])
*
* asserts:
* none
*
* returns: none
*/
void set_video_muxer(int muxer);
/*
* gets the video file basename
* args:
* none
*
* asserts:
* none
*
* returns: video file basename
*/
char *get_video_name();
/*
* sets the video file basename
* args:
* name: video file basename
*
* asserts:
* none
*
* returns: none
*/
void set_video_name(const char *name);
/*
* gets the video file path (to dir)
* args:
* none
*
* asserts:
* none
*
* returns: video file path
*/
char *get_video_path();
/*
* sets video path (to dir)
* args:
* path: video file path
*
* asserts:
* none
*
* returns: none
*/
void set_video_path(const char *path);
/*
* gets photo sufix flag
* args:
* none
*
* asserts:
* none
*
* returns: photo sufix flag
*/
int get_photo_sufix_flag();
/*
* gets photo format
* args:
* none
*
* asserts:
* none
*
* returns: photo format
*/
int get_photo_format();
/*
* sets photo format
* args:
* format - photo format (IMG_FMT_[JPG|BMP|PNG|RAW])
*
* asserts:
* none
*
* returns: none
*/
void set_photo_format(int format);
/*
* gets the photo file basename
* args:
* none
*
* asserts:
* none
*
* returns: photo file basename
*/
char *get_photo_name();
/*
* sets the photo file basename and image format
* args:
* name: photo file basename
*
* asserts:
* none
*
* returns: none
*/
void set_photo_name(const char *name);
/*
* gets the photo file path (to dir)
* args:
* none
*
* asserts:
* none
*
* returns: photo file path
*/
char *get_photo_path();
/*
* sets photo path (to dir)
* args:
* path: photo file path
*
* asserts:
* none
*
* returns: none
*/
void set_photo_path(const char *path);
#endif
| 5,600 |
C
|
.h
| 283 | 17.954064 | 81 | 0.539145 |
linuxdeepin/dtkmultimedia
| 3 | 16 | 2 |
LGPL-3.0
|
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
15,285,750 |
save_image.h
|
linuxdeepin_dtkmultimedia/src/multimedia/camera/libcam/libcam_v4l2core/save_image.h
|
/*******************************************************************************#
# guvcview http://guvcview.sourceforge.net #
# #
# Paulo Assis <[email protected]> #
# Nobuhiro Iwamatsu <[email protected]> #
# Add UYVY color support(Macbook iSight) #
# #
# This program is free software; you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation; either version 2 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software #
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #
# #
********************************************************************************/
#ifndef SAVE_IMAGE_H
#define SAVE_IMAGE_H
#include "gviewv4l2core.h"
#include "v4l2_core.h"
typedef struct _jpeg_encoder_ctx_t {
uint16_t image_width;
uint16_t image_height;
uint16_t mcu_width;
uint16_t mcu_height;
uint16_t horizontal_mcus;
uint16_t vertical_mcus;
uint16_t rows;
uint16_t cols;
uint16_t length_minus_mcu_width;
uint16_t length_minus_width;
uint16_t incr;
uint16_t mcu_width_size;
uint16_t offset;
int16_t ldc1;
int16_t ldc2;
int16_t ldc3;
uint32_t lcode;
uint16_t bitindex;
/* MCUs */
int16_t Y1 [64];
int16_t Y2 [64];
int16_t Temp [64];
int16_t CB [64];
int16_t CR [64];
/* Quantization Tables */
uint8_t Lqt [64];
uint8_t Cqt [64];
uint16_t ILqt [64];
uint16_t ICqt [64];
} jpeg_encoder_ctx_t;
/*
* save the current frame to file
* args:
* frame - pointer to frame buffer
* filename - output file name
* format - image type
* (IMG_FMT_RAW, IMG_FMT_JPG, IMG_FMT_PNG, IMG_FMT_BMP)
*
* asserts:
* vd is not null
*
* returns: error code
*/
int save_frame_image(v4l2_frame_buff_t *frame, const char *filename, int format);
/*
* save frame data to a jpeg file
* args:
* frame - pointer to frame buffer
* filename - filename string
*
* asserts:
* vd is not null
*
* returns: error code
*/
int save_image_jpeg(v4l2_frame_buff_t *frame, const char *filename);
/*
* save frame data to a bmp file
* args:
* frame - pointer to frame buffer
* filename - filename string
*
* asserts:
* vd is not null
*
* returns: error code
*/
int save_image_bmp(v4l2_frame_buff_t *frame, const char *filename);
/*
* save frame data into a png file
* args:
* frame - pointer to frame buffer
* filename - string with png filename name
*
* asserts:
* vd is not null
*
* returns: error code
*/
//int save_image_png(v4l2_frame_buff_t *frame, const char *filename);
/*
* encode jpeg
* args:
* input - pointer to input buffer (yuyv format)
* output - pointer to output buffer (jpeg format)
* jpeg_ctx - pointer to jpeg encoder context
* huff - huffman flag
*
*
* asserts:
* input is not null
* ouput is not null
* jpeg_ctx is not null
*
* returns: ouput size
*/
int encode_jpeg (uint8_t *input, uint8_t *output,
jpeg_encoder_ctx_t *jpeg_ctx, int huff);
/*
* init jpeg encoder context
* args:
* jpeg_ctx - pointer to jpeg encoder context
* image_width - image width (in pixels)
* image_height - image height (in pixels)
*
* asserts:
* jpeg_ctx is not null
*
* returns: none
*/
void initialization (jpeg_encoder_ctx_t *jpeg_ctx, int image_width, int image_height);
void initialize_quantization_tables (jpeg_encoder_ctx_t *jpeg_ctx);
#endif
| 4,715 |
C
|
.h
| 140 | 31.121429 | 86 | 0.534006 |
linuxdeepin/dtkmultimedia
| 3 | 16 | 2 |
LGPL-3.0
|
9/7/2024, 2:22:03 PM (Europe/Amsterdam)
| false | false | false | false | false | false | false | false |
15,678,617 |
gte.c
|
tirolino99_libpsx/project/jni/libpcsxcore/gte.c
|
/***************************************************************************
* PCSX-Revolution - PlayStation Emulator for Nintendo Wii *
* Copyright (C) 2009-2010 PCSX-Revolution Dev Team *
* <http://code.google.com/p/pcsx-revolution/> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02111-1307 USA. *
***************************************************************************/
/*
* GTE functions.
*/
#include "gte.h"
#include "psxmem.h"
#define VX(n) (n < 3 ? psxRegs.CP2D.p[n << 1].sw.l : psxRegs.CP2D.p[9].sw.l)
#define VY(n) (n < 3 ? psxRegs.CP2D.p[n << 1].sw.h : psxRegs.CP2D.p[10].sw.l)
#define VZ(n) (n < 3 ? psxRegs.CP2D.p[(n << 1) + 1].sw.l : psxRegs.CP2D.p[11].sw.l)
#define MX11(n) (n < 3 ? psxRegs.CP2C.p[(n << 3)].sw.l : 0)
#define MX12(n) (n < 3 ? psxRegs.CP2C.p[(n << 3)].sw.h : 0)
#define MX13(n) (n < 3 ? psxRegs.CP2C.p[(n << 3) + 1].sw.l : 0)
#define MX21(n) (n < 3 ? psxRegs.CP2C.p[(n << 3) + 1].sw.h : 0)
#define MX22(n) (n < 3 ? psxRegs.CP2C.p[(n << 3) + 2].sw.l : 0)
#define MX23(n) (n < 3 ? psxRegs.CP2C.p[(n << 3) + 2].sw.h : 0)
#define MX31(n) (n < 3 ? psxRegs.CP2C.p[(n << 3) + 3].sw.l : 0)
#define MX32(n) (n < 3 ? psxRegs.CP2C.p[(n << 3) + 3].sw.h : 0)
#define MX33(n) (n < 3 ? psxRegs.CP2C.p[(n << 3) + 4].sw.l : 0)
#define CV1(n) (n < 3 ? (s32)psxRegs.CP2C.r[(n << 3) + 5] : 0)
#define CV2(n) (n < 3 ? (s32)psxRegs.CP2C.r[(n << 3) + 6] : 0)
#define CV3(n) (n < 3 ? (s32)psxRegs.CP2C.r[(n << 3) + 7] : 0)
#define fSX(n) ((psxRegs.CP2D.p)[((n) + 12)].sw.l)
#define fSY(n) ((psxRegs.CP2D.p)[((n) + 12)].sw.h)
#define fSZ(n) ((psxRegs.CP2D.p)[((n) + 17)].w.l) /* (n == 0) => SZ1; */
#define gteVXY0 (psxRegs.CP2D.r[0])
#define gteVX0 (psxRegs.CP2D.p[0].sw.l)
#define gteVY0 (psxRegs.CP2D.p[0].sw.h)
#define gteVZ0 (psxRegs.CP2D.p[1].sw.l)
#define gteVXY1 (psxRegs.CP2D.r[2])
#define gteVX1 (psxRegs.CP2D.p[2].sw.l)
#define gteVY1 (psxRegs.CP2D.p[2].sw.h)
#define gteVZ1 (psxRegs.CP2D.p[3].sw.l)
#define gteVXY2 (psxRegs.CP2D.r[4])
#define gteVX2 (psxRegs.CP2D.p[4].sw.l)
#define gteVY2 (psxRegs.CP2D.p[4].sw.h)
#define gteVZ2 (psxRegs.CP2D.p[5].sw.l)
#define gteRGB (psxRegs.CP2D.r[6])
#define gteR (psxRegs.CP2D.p[6].b.l)
#define gteG (psxRegs.CP2D.p[6].b.h)
#define gteB (psxRegs.CP2D.p[6].b.h2)
#define gteCODE (psxRegs.CP2D.p[6].b.h3)
#define gteOTZ (psxRegs.CP2D.p[7].w.l)
#define gteIR0 (psxRegs.CP2D.p[8].sw.l)
#define gteIR1 (psxRegs.CP2D.p[9].sw.l)
#define gteIR2 (psxRegs.CP2D.p[10].sw.l)
#define gteIR3 (psxRegs.CP2D.p[11].sw.l)
#define gteSXY0 (psxRegs.CP2D.r[12])
#define gteSX0 (psxRegs.CP2D.p[12].sw.l)
#define gteSY0 (psxRegs.CP2D.p[12].sw.h)
#define gteSXY1 (psxRegs.CP2D.r[13])
#define gteSX1 (psxRegs.CP2D.p[13].sw.l)
#define gteSY1 (psxRegs.CP2D.p[13].sw.h)
#define gteSXY2 (psxRegs.CP2D.r[14])
#define gteSX2 (psxRegs.CP2D.p[14].sw.l)
#define gteSY2 (psxRegs.CP2D.p[14].sw.h)
#define gteSXYP (psxRegs.CP2D.r[15])
#define gteSXP (psxRegs.CP2D.p[15].sw.l)
#define gteSYP (psxRegs.CP2D.p[15].sw.h)
#define gteSZ0 (psxRegs.CP2D.p[16].w.l)
#define gteSZ1 (psxRegs.CP2D.p[17].w.l)
#define gteSZ2 (psxRegs.CP2D.p[18].w.l)
#define gteSZ3 (psxRegs.CP2D.p[19].w.l)
#define gteRGB0 (psxRegs.CP2D.r[20])
#define gteR0 (psxRegs.CP2D.p[20].b.l)
#define gteG0 (psxRegs.CP2D.p[20].b.h)
#define gteB0 (psxRegs.CP2D.p[20].b.h2)
#define gteCODE0 (psxRegs.CP2D.p[20].b.h3)
#define gteRGB1 (psxRegs.CP2D.r[21])
#define gteR1 (psxRegs.CP2D.p[21].b.l)
#define gteG1 (psxRegs.CP2D.p[21].b.h)
#define gteB1 (psxRegs.CP2D.p[21].b.h2)
#define gteCODE1 (psxRegs.CP2D.p[21].b.h3)
#define gteRGB2 (psxRegs.CP2D.r[22])
#define gteR2 (psxRegs.CP2D.p[22].b.l)
#define gteG2 (psxRegs.CP2D.p[22].b.h)
#define gteB2 (psxRegs.CP2D.p[22].b.h2)
#define gteCODE2 (psxRegs.CP2D.p[22].b.h3)
#define gteRES1 (psxRegs.CP2D.r[23])
#define gteMAC0 (((s32 *)psxRegs.CP2D.r)[24])
#define gteMAC1 (((s32 *)psxRegs.CP2D.r)[25])
#define gteMAC2 (((s32 *)psxRegs.CP2D.r)[26])
#define gteMAC3 (((s32 *)psxRegs.CP2D.r)[27])
#define gteIRGB (psxRegs.CP2D.r[28])
#define gteORGB (psxRegs.CP2D.r[29])
#define gteLZCS (psxRegs.CP2D.r[30])
#define gteLZCR (psxRegs.CP2D.r[31])
#define gteR11R12 (((s32 *)psxRegs.CP2C.r)[0])
#define gteR22R23 (((s32 *)psxRegs.CP2C.r)[2])
#define gteR11 (psxRegs.CP2C.p[0].sw.l)
#define gteR12 (psxRegs.CP2C.p[0].sw.h)
#define gteR13 (psxRegs.CP2C.p[1].sw.l)
#define gteR21 (psxRegs.CP2C.p[1].sw.h)
#define gteR22 (psxRegs.CP2C.p[2].sw.l)
#define gteR23 (psxRegs.CP2C.p[2].sw.h)
#define gteR31 (psxRegs.CP2C.p[3].sw.l)
#define gteR32 (psxRegs.CP2C.p[3].sw.h)
#define gteR33 (psxRegs.CP2C.p[4].sw.l)
#define gteTRX (((s32 *)psxRegs.CP2C.r)[5])
#define gteTRY (((s32 *)psxRegs.CP2C.r)[6])
#define gteTRZ (((s32 *)psxRegs.CP2C.r)[7])
#define gteL11 (psxRegs.CP2C.p[8].sw.l)
#define gteL12 (psxRegs.CP2C.p[8].sw.h)
#define gteL13 (psxRegs.CP2C.p[9].sw.l)
#define gteL21 (psxRegs.CP2C.p[9].sw.h)
#define gteL22 (psxRegs.CP2C.p[10].sw.l)
#define gteL23 (psxRegs.CP2C.p[10].sw.h)
#define gteL31 (psxRegs.CP2C.p[11].sw.l)
#define gteL32 (psxRegs.CP2C.p[11].sw.h)
#define gteL33 (psxRegs.CP2C.p[12].sw.l)
#define gteRBK (((s32 *)psxRegs.CP2C.r)[13])
#define gteGBK (((s32 *)psxRegs.CP2C.r)[14])
#define gteBBK (((s32 *)psxRegs.CP2C.r)[15])
#define gteLR1 (psxRegs.CP2C.p[16].sw.l)
#define gteLR2 (psxRegs.CP2C.p[16].sw.h)
#define gteLR3 (psxRegs.CP2C.p[17].sw.l)
#define gteLG1 (psxRegs.CP2C.p[17].sw.h)
#define gteLG2 (psxRegs.CP2C.p[18].sw.l)
#define gteLG3 (psxRegs.CP2C.p[18].sw.h)
#define gteLB1 (psxRegs.CP2C.p[19].sw.l)
#define gteLB2 (psxRegs.CP2C.p[19].sw.h)
#define gteLB3 (psxRegs.CP2C.p[20].sw.l)
#define gteRFC (((s32 *)psxRegs.CP2C.r)[21])
#define gteGFC (((s32 *)psxRegs.CP2C.r)[22])
#define gteBFC (((s32 *)psxRegs.CP2C.r)[23])
#define gteOFX (((s32 *)psxRegs.CP2C.r)[24])
#define gteOFY (((s32 *)psxRegs.CP2C.r)[25])
#define gteH (psxRegs.CP2C.p[26].sw.l)
#define gteDQA (psxRegs.CP2C.p[27].sw.l)
#define gteDQB (((s32 *)psxRegs.CP2C.r)[28])
#define gteZSF3 (psxRegs.CP2C.p[29].sw.l)
#define gteZSF4 (psxRegs.CP2C.p[30].sw.l)
#define gteFLAG (psxRegs.CP2C.r[31])
#define GTE_OP(op) ((op >> 20) & 31)
#define GTE_SF(op) ((op >> 19) & 1)
#define GTE_MX(op) ((op >> 17) & 3)
#define GTE_V(op) ((op >> 15) & 3)
#define GTE_CV(op) ((op >> 13) & 3)
#define GTE_CD(op) ((op >> 11) & 3) /* not used */
#define GTE_LM(op) ((op >> 10) & 1)
#define GTE_CT(op) ((op >> 6) & 15) /* not used */
#define GTE_FUNCT(op) (op & 63)
#define gteop (psxRegs.code & 0x1ffffff)
static inline s64 BOUNDS(s64 n_value, s64 n_max, int n_maxflag, s64 n_min, int n_minflag) {
if (n_value > n_max) {
gteFLAG |= n_maxflag;
} else if (n_value < n_min) {
gteFLAG |= n_minflag;
}
return n_value;
}
static inline s32 LIM(s32 value, s32 max, s32 min, u32 flag) {
s32 ret = value;
if (value > max) {
gteFLAG |= flag;
ret = max;
} else if (value < min) {
gteFLAG |= flag;
ret = min;
}
return ret;
}
#define A1(a) BOUNDS((a), 0x7fffffff, (1 << 30), -(s64)0x80000000, (1 << 31) | (1 << 27))
#define A2(a) BOUNDS((a), 0x7fffffff, (1 << 29), -(s64)0x80000000, (1 << 31) | (1 << 26))
#define A3(a) BOUNDS((a), 0x7fffffff, (1 << 28), -(s64)0x80000000, (1 << 31) | (1 << 25))
#define limB1(a, l) LIM((a), 0x7fff, -0x8000 * !l, (1 << 31) | (1 << 24))
#define limB2(a, l) LIM((a), 0x7fff, -0x8000 * !l, (1 << 31) | (1 << 23))
#define limB3(a, l) LIM((a), 0x7fff, -0x8000 * !l, (1 << 22))
#define limC1(a) LIM((a), 0x00ff, 0x0000, (1 << 21))
#define limC2(a) LIM((a), 0x00ff, 0x0000, (1 << 20))
#define limC3(a) LIM((a), 0x00ff, 0x0000, (1 << 19))
#define limD(a) LIM((a), 0xffff, 0x0000, (1 << 31) | (1 << 18))
static inline u32 limE(u32 result) {
if (result > 0x1ffff) {
gteFLAG |= (1 << 31) | (1 << 17);
return 0x1ffff;
}
return result;
}
#define F(a) BOUNDS((a), 0x7fffffff, (1 << 31) | (1 << 16), -(s64)0x80000000, (1 << 31) | (1 << 15))
#define limG1(a) LIM((a), 0x3ff, -0x400, (1 << 31) | (1 << 14))
#define limG2(a) LIM((a), 0x3ff, -0x400, (1 << 31) | (1 << 13))
#define limH(a) LIM((a), 0x1000, 0x0000, (1 << 12))
#include "gte_divider.h"
static inline u32 MFC2(int reg) {
switch (reg) {
case 1:
case 3:
case 5:
case 8:
case 9:
case 10:
case 11:
psxRegs.CP2D.r[reg] = (s32)psxRegs.CP2D.p[reg].sw.l;
break;
case 7:
case 16:
case 17:
case 18:
case 19:
psxRegs.CP2D.r[reg] = (u32)psxRegs.CP2D.p[reg].w.l;
break;
case 15:
psxRegs.CP2D.r[reg] = gteSXY2;
break;
case 28:
case 29:
psxRegs.CP2D.r[reg] = LIM(gteIR1 >> 7, 0x1f, 0, 0) |
(LIM(gteIR2 >> 7, 0x1f, 0, 0) << 5) |
(LIM(gteIR3 >> 7, 0x1f, 0, 0) << 10);
break;
}
return psxRegs.CP2D.r[reg];
}
static inline void MTC2(u32 value, int reg) {
switch (reg) {
case 15:
gteSXY0 = gteSXY1;
gteSXY1 = gteSXY2;
gteSXY2 = value;
gteSXYP = value;
break;
case 28:
gteIRGB = value;
gteIR1 = (value & 0x1f) << 7;
gteIR2 = (value & 0x3e0) << 2;
gteIR3 = (value & 0x7c00) >> 3;
break;
case 30:
{
int a;
gteLZCS = value;
a = gteLZCS;
if (a > 0) {
int i;
for (i = 31; (a & (1 << i)) == 0 && i >= 0; i--);
gteLZCR = 31 - i;
} else if (a < 0) {
int i;
a ^= 0xffffffff;
for (i = 31; (a & (1 << i)) == 0 && i >= 0; i--);
gteLZCR = 31 - i;
} else {
gteLZCR = 32;
}
}
break;
case 31:
return;
default:
psxRegs.CP2D.r[reg] = value;
}
}
static inline void CTC2(u32 value, int reg) {
switch (reg) {
case 4:
case 12:
case 20:
case 26:
case 27:
case 29:
case 30:
value = (s32)(s16)value;
break;
case 31:
value = value & 0x7ffff000;
if (value & 0x7f87e000) value |= 0x80000000;
break;
}
psxRegs.CP2C.r[reg] = value;
}
void gteMFC2() {
if (!_Rt_) return;
psxRegs.GPR.r[_Rt_] = MFC2(_Rd_);
}
void gteCFC2() {
if (!_Rt_) return;
psxRegs.GPR.r[_Rt_] = psxRegs.CP2C.r[_Rd_];
}
void gteMTC2() {
MTC2(psxRegs.GPR.r[_Rt_], _Rd_);
}
void gteCTC2() {
CTC2(psxRegs.GPR.r[_Rt_], _Rd_);
}
#define _oB_ (psxRegs.GPR.r[_Rs_] + _Imm_)
void gteLWC2() {
MTC2(psxMemRead32(_oB_), _Rt_);
}
void gteSWC2() {
psxMemWrite32(_oB_, MFC2(_Rt_));
}
#define DIVIDE DIVIDE_
static u32 DIVIDE_(s16 n, u16 d) {
if (n >= 0 && n < d * 2) {
s32 n_ = n;
return ((n_ << 16) + d / 2) / d;
//return (u32)((float)(n_ << 16) / (float)d + (float)0.5);
}
return 0xffffffff;
}
void gteRTPS() {
int quotient;
#ifdef GTE_LOG
GTE_LOG("GTE RTPS\n");
#endif
gteFLAG = 0;
gteMAC1 = A1((((s64)gteTRX << 12) + (gteR11 * gteVX0) + (gteR12 * gteVY0) + (gteR13 * gteVZ0)) >> 12);
gteMAC2 = A2((((s64)gteTRY << 12) + (gteR21 * gteVX0) + (gteR22 * gteVY0) + (gteR23 * gteVZ0)) >> 12);
gteMAC3 = A3((((s64)gteTRZ << 12) + (gteR31 * gteVX0) + (gteR32 * gteVY0) + (gteR33 * gteVZ0)) >> 12);
gteIR1 = limB1(gteMAC1, 0);
gteIR2 = limB2(gteMAC2, 0);
gteIR3 = limB3(gteMAC3, 0);
gteSZ0 = gteSZ1;
gteSZ1 = gteSZ2;
gteSZ2 = gteSZ3;
gteSZ3 = limD(gteMAC3);
quotient = limE(DIVIDE(gteH, gteSZ3));
gteSXY0 = gteSXY1;
gteSXY1 = gteSXY2;
gteSX2 = limG1(F((s64)gteOFX + ((s64)gteIR1 * quotient)) >> 16);
gteSY2 = limG2(F((s64)gteOFY + ((s64)gteIR2 * quotient)) >> 16);
gteMAC0 = F((s64)(gteDQB + ((s64)gteDQA * quotient)) >> 12);
gteIR0 = limH(gteMAC0);
}
void gteRTPT() {
int quotient;
int v;
s32 vx, vy, vz;
#ifdef GTE_LOG
GTE_LOG("GTE RTPT\n");
#endif
gteFLAG = 0;
gteSZ0 = gteSZ3;
for (v = 0; v < 3; v++) {
vx = VX(v);
vy = VY(v);
vz = VZ(v);
gteMAC1 = A1((((s64)gteTRX << 12) + (gteR11 * vx) + (gteR12 * vy) + (gteR13 * vz)) >> 12);
gteMAC2 = A2((((s64)gteTRY << 12) + (gteR21 * vx) + (gteR22 * vy) + (gteR23 * vz)) >> 12);
gteMAC3 = A3((((s64)gteTRZ << 12) + (gteR31 * vx) + (gteR32 * vy) + (gteR33 * vz)) >> 12);
gteIR1 = limB1(gteMAC1, 0);
gteIR2 = limB2(gteMAC2, 0);
gteIR3 = limB3(gteMAC3, 0);
fSZ(v) = limD(gteMAC3);
quotient = limE(DIVIDE(gteH, fSZ(v)));
fSX(v) = limG1(F((s64)gteOFX + ((s64)gteIR1 * quotient)) >> 16);
fSY(v) = limG2(F((s64)gteOFY + ((s64)gteIR2 * quotient)) >> 16);
}
gteMAC0 = F((s64)(gteDQB + ((s64)gteDQA * quotient)) >> 12);
gteIR0 = limH(gteMAC0);
}
void gteMVMVA() {
int shift = 12 * GTE_SF(gteop);
int mx = GTE_MX(gteop);
int v = GTE_V(gteop);
int cv = GTE_CV(gteop);
int lm = GTE_LM(gteop);
s32 vx = VX(v);
s32 vy = VY(v);
s32 vz = VZ(v);
#ifdef GTE_LOG
GTE_LOG("GTE MVMVA\n");
#endif
gteFLAG = 0;
gteMAC1 = A1((((s64)CV1(cv) << 12) + (MX11(mx) * vx) + (MX12(mx) * vy) + (MX13(mx) * vz)) >> shift);
gteMAC2 = A2((((s64)CV2(cv) << 12) + (MX21(mx) * vx) + (MX22(mx) * vy) + (MX23(mx) * vz)) >> shift);
gteMAC3 = A3((((s64)CV3(cv) << 12) + (MX31(mx) * vx) + (MX32(mx) * vy) + (MX33(mx) * vz)) >> shift);
gteIR1 = limB1(gteMAC1, lm);
gteIR2 = limB2(gteMAC2, lm);
gteIR3 = limB3(gteMAC3, lm);
}
void gteNCLIP() {
#ifdef GTE_LOG
GTE_LOG("GTE NCLIP\n");
#endif
gteFLAG = 0;
gteMAC0 = F((s64)gteSX0 * (gteSY1 - gteSY2) +
gteSX1 * (gteSY2 - gteSY0) +
gteSX2 * (gteSY0 - gteSY1));
}
void gteAVSZ3() {
#ifdef GTE_LOG
GTE_LOG("GTE AVSZ3\n");
#endif
gteFLAG = 0;
gteMAC0 = F((s64)(gteZSF3 * gteSZ1) + (gteZSF3 * gteSZ2) + (gteZSF3 * gteSZ3));
gteOTZ = limD(gteMAC0 >> 12);
}
void gteAVSZ4() {
#ifdef GTE_LOG
GTE_LOG("GTE AVSZ4\n");
#endif
gteFLAG = 0;
gteMAC0 = F((s64)(gteZSF4 * (gteSZ0 + gteSZ1 + gteSZ2 + gteSZ3)));
gteOTZ = limD(gteMAC0 >> 12);
}
void gteSQR() {
int shift = 12 * GTE_SF(gteop);
int lm = GTE_LM(gteop);
#ifdef GTE_LOG
GTE_LOG("GTE SQR\n");
#endif
gteFLAG = 0;
gteMAC1 = A1((gteIR1 * gteIR1) >> shift);
gteMAC2 = A2((gteIR2 * gteIR2) >> shift);
gteMAC3 = A3((gteIR3 * gteIR3) >> shift);
gteIR1 = limB1(gteMAC1, lm);
gteIR2 = limB2(gteMAC2, lm);
gteIR3 = limB3(gteMAC3, lm);
}
void gteNCCS() {
#ifdef GTE_LOG
GTE_LOG("GTE NCCS\n");
#endif
gteFLAG = 0;
gteMAC1 = A1((((s64)gteL11 * gteVX0) + (gteL12 * gteVY0) + (gteL13 * gteVZ0)) >> 12);
gteMAC2 = A2((((s64)gteL21 * gteVX0) + (gteL22 * gteVY0) + (gteL23 * gteVZ0)) >> 12);
gteMAC3 = A3((((s64)gteL31 * gteVX0) + (gteL32 * gteVY0) + (gteL33 * gteVZ0)) >> 12);
gteIR1 = limB1(gteMAC1, 1);
gteIR2 = limB2(gteMAC2, 1);
gteIR3 = limB3(gteMAC3, 1);
gteMAC1 = A1((((s64)gteRBK << 12) + (gteLR1 * gteIR1) + (gteLR2 * gteIR2) + (gteLR3 * gteIR3)) >> 12);
gteMAC2 = A2((((s64)gteGBK << 12) + (gteLG1 * gteIR1) + (gteLG2 * gteIR2) + (gteLG3 * gteIR3)) >> 12);
gteMAC3 = A3((((s64)gteBBK << 12) + (gteLB1 * gteIR1) + (gteLB2 * gteIR2) + (gteLB3 * gteIR3)) >> 12);
gteIR1 = limB1(gteMAC1, 1);
gteIR2 = limB2(gteMAC2, 1);
gteIR3 = limB3(gteMAC3, 1);
gteMAC1 = A1(((s64)gteR * gteIR1) >> 8);
gteMAC2 = A2(((s64)gteG * gteIR2) >> 8);
gteMAC3 = A3(((s64)gteB * gteIR3) >> 8);
gteIR1 = limB1(gteMAC1, 1);
gteIR2 = limB2(gteMAC2, 1);
gteIR3 = limB3(gteMAC3, 1);
gteRGB0 = gteRGB1;
gteRGB1 = gteRGB2;
gteCODE2 = gteCODE;
gteR2 = limC1(gteMAC1 >> 4);
gteG2 = limC2(gteMAC2 >> 4);
gteB2 = limC3(gteMAC3 >> 4);
}
void gteNCCT() {
int v;
s32 vx, vy, vz;
#ifdef GTE_LOG
GTE_LOG("GTE NCCT\n");
#endif
gteFLAG = 0;
for (v = 0; v < 3; v++) {
vx = VX(v);
vy = VY(v);
vz = VZ(v);
gteMAC1 = A1((((s64)gteL11 * vx) + (gteL12 * vy) + (gteL13 * vz)) >> 12);
gteMAC2 = A2((((s64)gteL21 * vx) + (gteL22 * vy) + (gteL23 * vz)) >> 12);
gteMAC3 = A3((((s64)gteL31 * vx) + (gteL32 * vy) + (gteL33 * vz)) >> 12);
gteIR1 = limB1(gteMAC1, 1);
gteIR2 = limB2(gteMAC2, 1);
gteIR3 = limB3(gteMAC3, 1);
gteMAC1 = A1((((s64)gteRBK << 12) + (gteLR1 * gteIR1) + (gteLR2 * gteIR2) + (gteLR3 * gteIR3)) >> 12);
gteMAC2 = A2((((s64)gteGBK << 12) + (gteLG1 * gteIR1) + (gteLG2 * gteIR2) + (gteLG3 * gteIR3)) >> 12);
gteMAC3 = A3((((s64)gteBBK << 12) + (gteLB1 * gteIR1) + (gteLB2 * gteIR2) + (gteLB3 * gteIR3)) >> 12);
gteIR1 = limB1(gteMAC1, 1);
gteIR2 = limB2(gteMAC2, 1);
gteIR3 = limB3(gteMAC3, 1);
gteMAC1 = A1(((s64)gteR * gteIR1) >> 8);
gteMAC2 = A2(((s64)gteG * gteIR2) >> 8);
gteMAC3 = A3(((s64)gteB * gteIR3) >> 8);
gteRGB0 = gteRGB1;
gteRGB1 = gteRGB2;
gteCODE2 = gteCODE;
gteR2 = limC1(gteMAC1 >> 4);
gteG2 = limC2(gteMAC2 >> 4);
gteB2 = limC3(gteMAC3 >> 4);
}
gteIR1 = limB1(gteMAC1, 1);
gteIR2 = limB2(gteMAC2, 1);
gteIR3 = limB3(gteMAC3, 1);
}
void gteNCDS() {
#ifdef GTE_LOG
GTE_LOG("GTE NCDS\n");
#endif
gteFLAG = 0;
gteMAC1 = A1((((s64)gteL11 * gteVX0) + (gteL12 * gteVY0) + (gteL13 * gteVZ0)) >> 12);
gteMAC2 = A2((((s64)gteL21 * gteVX0) + (gteL22 * gteVY0) + (gteL23 * gteVZ0)) >> 12);
gteMAC3 = A3((((s64)gteL31 * gteVX0) + (gteL32 * gteVY0) + (gteL33 * gteVZ0)) >> 12);
gteIR1 = limB1(gteMAC1, 1);
gteIR2 = limB2(gteMAC2, 1);
gteIR3 = limB3(gteMAC3, 1);
gteMAC1 = A1((((s64)gteRBK << 12) + (gteLR1 * gteIR1) + (gteLR2 * gteIR2) + (gteLR3 * gteIR3)) >> 12);
gteMAC2 = A2((((s64)gteGBK << 12) + (gteLG1 * gteIR1) + (gteLG2 * gteIR2) + (gteLG3 * gteIR3)) >> 12);
gteMAC3 = A3((((s64)gteBBK << 12) + (gteLB1 * gteIR1) + (gteLB2 * gteIR2) + (gteLB3 * gteIR3)) >> 12);
gteIR1 = limB1(gteMAC1, 1);
gteIR2 = limB2(gteMAC2, 1);
gteIR3 = limB3(gteMAC3, 1);
gteMAC1 = A1(((((s64)gteR << 4) * gteIR1) + (gteIR0 * limB1(gteRFC - ((gteR * gteIR1) >> 8), 0))) >> 12);
gteMAC2 = A2(((((s64)gteG << 4) * gteIR2) + (gteIR0 * limB2(gteGFC - ((gteG * gteIR2) >> 8), 0))) >> 12);
gteMAC3 = A3(((((s64)gteB << 4) * gteIR3) + (gteIR0 * limB3(gteBFC - ((gteB * gteIR3) >> 8), 0))) >> 12);
gteIR1 = limB1(gteMAC1, 1);
gteIR2 = limB2(gteMAC2, 1);
gteIR3 = limB3(gteMAC3, 1);
gteRGB0 = gteRGB1;
gteRGB1 = gteRGB2;
gteCODE2 = gteCODE;
gteR2 = limC1(gteMAC1 >> 4);
gteG2 = limC2(gteMAC2 >> 4);
gteB2 = limC3(gteMAC3 >> 4);
}
void gteNCDT() {
int v;
s32 vx, vy, vz;
#ifdef GTE_LOG
GTE_LOG("GTE NCDT\n");
#endif
gteFLAG = 0;
for (v = 0; v < 3; v++) {
vx = VX(v);
vy = VY(v);
vz = VZ(v);
gteMAC1 = A1((((s64)gteL11 * vx) + (gteL12 * vy) + (gteL13 * vz)) >> 12);
gteMAC2 = A2((((s64)gteL21 * vx) + (gteL22 * vy) + (gteL23 * vz)) >> 12);
gteMAC3 = A3((((s64)gteL31 * vx) + (gteL32 * vy) + (gteL33 * vz)) >> 12);
gteIR1 = limB1(gteMAC1, 1);
gteIR2 = limB2(gteMAC2, 1);
gteIR3 = limB3(gteMAC3, 1);
gteMAC1 = A1((((s64)gteRBK << 12) + (gteLR1 * gteIR1) + (gteLR2 * gteIR2) + (gteLR3 * gteIR3)) >> 12);
gteMAC2 = A2((((s64)gteGBK << 12) + (gteLG1 * gteIR1) + (gteLG2 * gteIR2) + (gteLG3 * gteIR3)) >> 12);
gteMAC3 = A3((((s64)gteBBK << 12) + (gteLB1 * gteIR1) + (gteLB2 * gteIR2) + (gteLB3 * gteIR3)) >> 12);
gteIR1 = limB1(gteMAC1, 1);
gteIR2 = limB2(gteMAC2, 1);
gteIR3 = limB3(gteMAC3, 1);
gteMAC1 = A1(((((s64)gteR << 4) * gteIR1) + (gteIR0 * limB1(gteRFC - ((gteR * gteIR1) >> 8), 0))) >> 12);
gteMAC2 = A2(((((s64)gteG << 4) * gteIR2) + (gteIR0 * limB2(gteGFC - ((gteG * gteIR2) >> 8), 0))) >> 12);
gteMAC3 = A3(((((s64)gteB << 4) * gteIR3) + (gteIR0 * limB3(gteBFC - ((gteB * gteIR3) >> 8), 0))) >> 12);
gteRGB0 = gteRGB1;
gteRGB1 = gteRGB2;
gteCODE2 = gteCODE;
gteR2 = limC1(gteMAC1 >> 4);
gteG2 = limC2(gteMAC2 >> 4);
gteB2 = limC3(gteMAC3 >> 4);
}
gteIR1 = limB1(gteMAC1, 1);
gteIR2 = limB2(gteMAC2, 1);
gteIR3 = limB3(gteMAC3, 1);
}
void gteOP() {
int shift = 12 * GTE_SF(gteop);
int lm = GTE_LM(gteop);
#ifdef GTE_LOG
GTE_LOG("GTE OP\n");
#endif
gteFLAG = 0;
gteMAC1 = A1(((s64)(gteR22 * gteIR3) - (gteR33 * gteIR2)) >> shift);
gteMAC2 = A2(((s64)(gteR33 * gteIR1) - (gteR11 * gteIR3)) >> shift);
gteMAC3 = A3(((s64)(gteR11 * gteIR2) - (gteR22 * gteIR1)) >> shift);
gteIR1 = limB1(gteMAC1, lm);
gteIR2 = limB2(gteMAC2, lm);
gteIR3 = limB3(gteMAC3, lm);
}
void gteDCPL() {
int lm = GTE_LM(gteop);
s64 RIR1 = ((s64)gteR * gteIR1) >> 8;
s64 GIR2 = ((s64)gteG * gteIR2) >> 8;
s64 BIR3 = ((s64)gteB * gteIR3) >> 8;
#ifdef GTE_LOG
GTE_LOG("GTE DCPL\n");
#endif
gteFLAG = 0;
gteMAC1 = A1(RIR1 + ((gteIR0 * limB1(gteRFC - RIR1, 0)) >> 12));
gteMAC2 = A2(GIR2 + ((gteIR0 * limB1(gteGFC - GIR2, 0)) >> 12));
gteMAC3 = A3(BIR3 + ((gteIR0 * limB1(gteBFC - BIR3, 0)) >> 12));
gteIR1 = limB1(gteMAC1, lm);
gteIR2 = limB2(gteMAC2, lm);
gteIR3 = limB3(gteMAC3, lm);
gteRGB0 = gteRGB1;
gteRGB1 = gteRGB2;
gteCODE2 = gteCODE;
gteR2 = limC1(gteMAC1 >> 4);
gteG2 = limC2(gteMAC2 >> 4);
gteB2 = limC3(gteMAC3 >> 4);
}
void gteGPF() {
int shift = 12 * GTE_SF(gteop);
#ifdef GTE_LOG
GTE_LOG("GTE GPF\n");
#endif
gteFLAG = 0;
gteMAC1 = A1(((s64)gteIR0 * gteIR1) >> shift);
gteMAC2 = A2(((s64)gteIR0 * gteIR2) >> shift);
gteMAC3 = A3(((s64)gteIR0 * gteIR3) >> shift);
gteIR1 = limB1(gteMAC1, 0);
gteIR2 = limB2(gteMAC2, 0);
gteIR3 = limB3(gteMAC3, 0);
gteRGB0 = gteRGB1;
gteRGB1 = gteRGB2;
gteCODE2 = gteCODE;
gteR2 = limC1(gteMAC1 >> 4);
gteG2 = limC2(gteMAC2 >> 4);
gteB2 = limC3(gteMAC3 >> 4);
}
void gteGPL() {
int shift = 12 * GTE_SF(gteop);
#ifdef GTE_LOG
GTE_LOG("GTE GPL\n");
#endif
gteFLAG = 0;
gteMAC1 = A1((((s64)gteMAC1 << shift) + (gteIR0 * gteIR1)) >> shift);
gteMAC2 = A2((((s64)gteMAC2 << shift) + (gteIR0 * gteIR2)) >> shift);
gteMAC3 = A3((((s64)gteMAC3 << shift) + (gteIR0 * gteIR3)) >> shift);
gteIR1 = limB1(gteMAC1, 0);
gteIR2 = limB2(gteMAC2, 0);
gteIR3 = limB3(gteMAC3, 0);
gteRGB0 = gteRGB1;
gteRGB1 = gteRGB2;
gteCODE2 = gteCODE;
gteR2 = limC1(gteMAC1 >> 4);
gteG2 = limC2(gteMAC2 >> 4);
gteB2 = limC3(gteMAC3 >> 4);
}
void gteDPCS() {
int shift = 12 * GTE_SF(gteop);
#ifdef GTE_LOG
GTE_LOG("GTE DPCS\n");
#endif
gteFLAG = 0;
gteMAC1 = A1(((gteR << 16) + (gteIR0 * limB1(A1((s64)gteRFC - (gteR << 4)) << (12 - shift), 0))) >> 12);
gteMAC2 = A2(((gteG << 16) + (gteIR0 * limB2(A2((s64)gteGFC - (gteG << 4)) << (12 - shift), 0))) >> 12);
gteMAC3 = A3(((gteB << 16) + (gteIR0 * limB3(A3((s64)gteBFC - (gteB << 4)) << (12 - shift), 0))) >> 12);
gteIR1 = limB1(gteMAC1, 0);
gteIR2 = limB2(gteMAC2, 0);
gteIR3 = limB3(gteMAC3, 0);
gteRGB0 = gteRGB1;
gteRGB1 = gteRGB2;
gteCODE2 = gteCODE;
gteR2 = limC1(gteMAC1 >> 4);
gteG2 = limC2(gteMAC2 >> 4);
gteB2 = limC3(gteMAC3 >> 4);
}
void gteDPCT() {
int v;
#ifdef GTE_LOG
GTE_LOG("GTE DPCT\n");
#endif
gteFLAG = 0;
for (v = 0; v < 3; v++) {
gteMAC1 = A1((((s64)gteR0 << 16) + ((s64)gteIR0 * (limB1(gteRFC - (gteR0 << 4), 0)))) >> 12);
gteMAC2 = A2((((s64)gteG0 << 16) + ((s64)gteIR0 * (limB1(gteGFC - (gteG0 << 4), 0)))) >> 12);
gteMAC3 = A3((((s64)gteB0 << 16) + ((s64)gteIR0 * (limB1(gteBFC - (gteB0 << 4), 0)))) >> 12);
gteRGB0 = gteRGB1;
gteRGB1 = gteRGB2;
gteCODE2 = gteCODE;
gteR2 = limC1(gteMAC1 >> 4);
gteG2 = limC2(gteMAC2 >> 4);
gteB2 = limC3(gteMAC3 >> 4);
}
gteIR1 = limB1(gteMAC1, 0);
gteIR2 = limB2(gteMAC2, 0);
gteIR3 = limB3(gteMAC3, 0);
}
void gteNCS() {
#ifdef GTE_LOG
GTE_LOG("GTE NCS\n");
#endif
gteFLAG = 0;
gteMAC1 = A1((((s64)gteL11 * gteVX0) + (gteL12 * gteVY0) + (gteL13 * gteVZ0)) >> 12);
gteMAC2 = A2((((s64)gteL21 * gteVX0) + (gteL22 * gteVY0) + (gteL23 * gteVZ0)) >> 12);
gteMAC3 = A3((((s64)gteL31 * gteVX0) + (gteL32 * gteVY0) + (gteL33 * gteVZ0)) >> 12);
gteIR1 = limB1(gteMAC1, 1);
gteIR2 = limB2(gteMAC2, 1);
gteIR3 = limB3(gteMAC3, 1);
gteMAC1 = A1((((s64)gteRBK << 12) + (gteLR1 * gteIR1) + (gteLR2 * gteIR2) + (gteLR3 * gteIR3)) >> 12);
gteMAC2 = A2((((s64)gteGBK << 12) + (gteLG1 * gteIR1) + (gteLG2 * gteIR2) + (gteLG3 * gteIR3)) >> 12);
gteMAC3 = A3((((s64)gteBBK << 12) + (gteLB1 * gteIR1) + (gteLB2 * gteIR2) + (gteLB3 * gteIR3)) >> 12);
gteIR1 = limB1(gteMAC1, 1);
gteIR2 = limB2(gteMAC2, 1);
gteIR3 = limB3(gteMAC3, 1);
gteRGB0 = gteRGB1;
gteRGB1 = gteRGB2;
gteCODE2 = gteCODE;
gteR2 = limC1(gteMAC1 >> 4);
gteG2 = limC2(gteMAC2 >> 4);
gteB2 = limC3(gteMAC3 >> 4);
}
void gteNCT() {
int v;
s32 vx, vy, vz;
#ifdef GTE_LOG
GTE_LOG("GTE NCT\n");
#endif
gteFLAG = 0;
for (v = 0; v < 3; v++) {
vx = VX(v);
vy = VY(v);
vz = VZ(v);
gteMAC1 = A1((((s64)gteL11 * vx) + (gteL12 * vy) + (gteL13 * vz)) >> 12);
gteMAC2 = A2((((s64)gteL21 * vx) + (gteL22 * vy) + (gteL23 * vz)) >> 12);
gteMAC3 = A3((((s64)gteL31 * vx) + (gteL32 * vy) + (gteL33 * vz)) >> 12);
gteIR1 = limB1(gteMAC1, 1);
gteIR2 = limB2(gteMAC2, 1);
gteIR3 = limB3(gteMAC3, 1);
gteMAC1 = A1((((s64)gteRBK << 12) + (gteLR1 * gteIR1) + (gteLR2 * gteIR2) + (gteLR3 * gteIR3)) >> 12);
gteMAC2 = A2((((s64)gteGBK << 12) + (gteLG1 * gteIR1) + (gteLG2 * gteIR2) + (gteLG3 * gteIR3)) >> 12);
gteMAC3 = A3((((s64)gteBBK << 12) + (gteLB1 * gteIR1) + (gteLB2 * gteIR2) + (gteLB3 * gteIR3)) >> 12);
gteRGB0 = gteRGB1;
gteRGB1 = gteRGB2;
gteCODE2 = gteCODE;
gteR2 = limC1(gteMAC1 >> 4);
gteG2 = limC2(gteMAC2 >> 4);
gteB2 = limC3(gteMAC3 >> 4);
}
gteIR1 = limB1(gteMAC1, 1);
gteIR2 = limB2(gteMAC2, 1);
gteIR3 = limB3(gteMAC3, 1);
}
void gteCC() {
#ifdef GTE_LOG
GTE_LOG("GTE CC\n");
#endif
gteFLAG = 0;
gteMAC1 = A1((((s64)gteRBK << 12) + (gteLR1 * gteIR1) + (gteLR2 * gteIR2) + (gteLR3 * gteIR3)) >> 12);
gteMAC2 = A2((((s64)gteGBK << 12) + (gteLG1 * gteIR1) + (gteLG2 * gteIR2) + (gteLG3 * gteIR3)) >> 12);
gteMAC3 = A3((((s64)gteBBK << 12) + (gteLB1 * gteIR1) + (gteLB2 * gteIR2) + (gteLB3 * gteIR3)) >> 12);
gteIR1 = limB1(gteMAC1, 1);
gteIR2 = limB2(gteMAC2, 1);
gteIR3 = limB3(gteMAC3, 1);
gteMAC1 = A1(((s64)gteR * gteIR1) >> 8);
gteMAC2 = A2(((s64)gteG * gteIR2) >> 8);
gteMAC3 = A3(((s64)gteB * gteIR3) >> 8);
gteIR1 = limB1(gteMAC1, 1);
gteIR2 = limB2(gteMAC2, 1);
gteIR3 = limB3(gteMAC3, 1);
gteRGB0 = gteRGB1;
gteRGB1 = gteRGB2;
gteCODE2 = gteCODE;
gteR2 = limC1(gteMAC1 >> 4);
gteG2 = limC2(gteMAC2 >> 4);
gteB2 = limC3(gteMAC3 >> 4);
}
void gteINTPL() {
int shift = 12 * GTE_SF(gteop);
int lm = GTE_LM(gteop);
#ifdef GTE_LOG
GTE_LOG("GTE INTPL\n");
#endif
gteFLAG = 0;
gteMAC1 = A1(((gteIR1 << 12) + (gteIR0 * limB1(((s64)gteRFC - gteIR1), 0))) >> shift);
gteMAC2 = A2(((gteIR2 << 12) + (gteIR0 * limB2(((s64)gteGFC - gteIR2), 0))) >> shift);
gteMAC3 = A3(((gteIR3 << 12) + (gteIR0 * limB3(((s64)gteBFC - gteIR3), 0))) >> shift);
gteIR1 = limB1(gteMAC1, lm);
gteIR2 = limB2(gteMAC2, lm);
gteIR3 = limB3(gteMAC3, lm);
gteRGB0 = gteRGB1;
gteRGB1 = gteRGB2;
gteCODE2 = gteCODE;
gteR2 = limC1(gteMAC1 >> 4);
gteG2 = limC2(gteMAC2 >> 4);
gteB2 = limC3(gteMAC3 >> 4);
}
void gteCDP() {
#ifdef GTE_LOG
GTE_LOG("GTE CDP\n");
#endif
gteFLAG = 0;
gteMAC1 = A1((((s64)gteRBK << 12) + (gteLR1 * gteIR1) + (gteLR2 * gteIR2) + (gteLR3 * gteIR3)) >> 12);
gteMAC2 = A2((((s64)gteGBK << 12) + (gteLG1 * gteIR1) + (gteLG2 * gteIR2) + (gteLG3 * gteIR3)) >> 12);
gteMAC3 = A3((((s64)gteBBK << 12) + (gteLB1 * gteIR1) + (gteLB2 * gteIR2) + (gteLB3 * gteIR3)) >> 12);
gteIR1 = limB1(gteMAC1, 1);
gteIR2 = limB2(gteMAC2, 1);
gteIR3 = limB3(gteMAC3, 1);
gteMAC1 = A1(((((s64)gteR << 4) * gteIR1) + (gteIR0 * limB1(gteRFC - ((gteR * gteIR1) >> 8), 0))) >> 12);
gteMAC2 = A2(((((s64)gteG << 4) * gteIR2) + (gteIR0 * limB2(gteGFC - ((gteG * gteIR2) >> 8), 0))) >> 12);
gteMAC3 = A3(((((s64)gteB << 4) * gteIR3) + (gteIR0 * limB3(gteBFC - ((gteB * gteIR3) >> 8), 0))) >> 12);
gteIR1 = limB1(gteMAC1, 1);
gteIR2 = limB2(gteMAC2, 1);
gteIR3 = limB3(gteMAC3, 1);
gteRGB0 = gteRGB1;
gteRGB1 = gteRGB2;
gteCODE2 = gteCODE;
gteR2 = limC1(gteMAC1 >> 4);
gteG2 = limC2(gteMAC2 >> 4);
gteB2 = limC3(gteMAC3 >> 4);
}
| 28,204 |
C
|
.c
| 800 | 33.1375 | 107 | 0.59652 |
tirolino99/libpsx
| 2 | 12 | 0 |
GPL-2.0
|
9/7/2024, 2:31:37 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,678,623 |
LnxMain.c
|
tirolino99_libpsx/project/jni/libpcsxcore/LnxMain.c
|
/* Pcsx - Pc Psx Emulator
* Copyright (C) 1999-2002 Pcsx Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1307 USA
*/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>
#include <dlfcn.h>
#include <sys/mman.h>
#include <errno.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#include <dirent.h>
#include <sys/stat.h>
#include "sio.h"
#include "psxcommon.h"
enum {
RUN = 0,
RUN_CD,
};
#ifdef PANDORA
int main(int argc, char *argv[]) {
char file[MAXPATHLEN] = "";
char path[MAXPATHLEN];
int runcd = RUN;
int loadst = 0;
int i;
#ifdef ENABLE_NLS
setlocale (LC_ALL, "");
bindtextdomain (GETTEXT_PACKAGE, LOCALE_DIR);
bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
textdomain (GETTEXT_PACKAGE);
#endif
// what is the name of the config file?
// it may be redefined by -cfg on the command line
strcpy(cfgfile_basename, "pcsx.cfg");
// read command line options
for (i = 1; i < argc; i++) {
if (!strcmp(argv[i], "-runcd")) runcd = RUN_CD;
else if (!strcmp(argv[i], "-nogui")) UseGui = FALSE;
else if (!strcmp(argv[i], "-psxout")) Config.PsxOut = 1;
else if (!strcmp(argv[i], "-load")) loadst = atol(argv[++i]);
else if (!strcmp(argv[i], "-cfg")) {
if (i+1 >= argc) break;
strncpy(cfgfile_basename, argv[++i], MAXPATHLEN-100); /* TODO buffer overruns */
printf("Using config file %s.\n", cfgfile_basename);
}
else if (!strcmp(argv[i], "-cdfile")) {
char isofilename[MAXPATHLEN];
if (i+1 >= argc) break;
strncpy(isofilename, argv[++i], MAXPATHLEN);
if (isofilename[0] != '/') {
getcwd(path, MAXPATHLEN);
if (strlen(path) + strlen(isofilename) + 1 < MAXPATHLEN) {
strcat(path, "/");
strcat(path, isofilename);
strcpy(isofilename, path);
} else
isofilename[0] = 0;
}
SetIsoFile(isofilename);
runcd = RUN_CD;
UseGui = FALSE;
}
else if (!strcmp(argv[i], "-h") ||
!strcmp(argv[i], "-help") ||
!strcmp(argv[i], "--help")) {
printf(PACKAGE_STRING "\n");
printf("%s\n", _(
" pcsx [options] [file]\n"
"\toptions:\n"
"\t-runcd\t\tRuns CD-ROM\n"
"\t-cdfile FILE\tRuns a CD image file\n"
"\t-nogui\t\tDon't open the GTK GUI\n"
"\t-cfg FILE\tLoads desired configuration file (default: ~/.pcsx/pcsx.cfg)\n"
"\t-psxout\t\tEnable PSX output\n"
"\t-load STATENUM\tLoads savestate STATENUM (1-9)\n"
"\t-h -help\tDisplay this message\n"
"\tfile\t\tLoads file\n"));
return 0;
} else {
strncpy(file, argv[i], MAXPATHLEN);
if (file[0] != '/') {
getcwd(path, MAXPATHLEN);
if (strlen(path) + strlen(file) + 1 < MAXPATHLEN) {
strcat(path, "/");
strcat(path, file);
strcpy(file, path);
} else
file[0] = 0;
}
}
}
memset(&Config, 0, sizeof(PcsxConfig));
strcpy(Config.Net, "Disabled");
if (UseGui) gtk_init(NULL, NULL);
CheckSubDir();
ScanAllPlugins();
// try to load config
// if the config file doesn't exist
if (LoadConfig() == -1) {
if (!UseGui) {
printf(_("PCSX cannot be configured without using the GUI -- you should restart without -nogui.\n"));
return 1;
}
// Uh oh, no config file found, use some defaults
Config.PsxAuto = 1;
gchar *str_bios_dir = g_strconcat(getenv("HOME"), BIOS_DIR, NULL);
strcpy(Config.BiosDir, str_bios_dir);
g_free(str_bios_dir);
gchar *str_plugin_dir = g_strconcat(getenv("HOME"), PLUGINS_DIR, NULL);
strcpy(Config.PluginsDir, str_plugin_dir);
g_free(str_plugin_dir);
gtk_init(NULL, NULL);
// Update available plugins, but not GUI
UpdatePluginsBIOS();
// Pick some defaults, if they're available
set_default_plugin(GpuConfS.plist[0], Config.Gpu);
set_default_plugin(SpuConfS.plist[0], Config.Spu);
set_default_plugin(CdrConfS.plist[0], Config.Cdr);
set_default_plugin(Pad1ConfS.plist[0], Config.Pad1);
set_default_plugin(Pad2ConfS.plist[0], Config.Pad2);
set_default_plugin(BiosConfS.plist[0], Config.Bios);
// create & load default memcards if they don't exist
CreateMemcard("card1.mcd", Config.Mcd1);
CreateMemcard("card2.mcd", Config.Mcd2);
LoadMcds(Config.Mcd1, Config.Mcd2);
SaveConfig();
}
gchar *str_patches_dir = g_strconcat(getenv("HOME"), PATCHES_DIR, NULL);
strcpy(Config.PatchesDir, str_patches_dir);
g_free(str_patches_dir);
// switch to plugin dotdir
// this lets plugins work without modification!
gchar *plugin_default_dir = g_build_filename(getenv("HOME"), PLUGINS_DIR, NULL);
chdir(plugin_default_dir);
g_free(plugin_default_dir);
if (UseGui) SetIsoFile(NULL);
if (SysInit() == -1) return 1;
if (UseGui) {
StartGui();
} else {
// the following only occurs if the gui isn't started
if (LoadPlugins() == -1) {
SysErrorMessage(_("Error"), _("Failed loading plugins!"));
return 1;
}
#if 0
if (OpenPlugins() == -1 || plugins_configured() == FALSE) {
return 1;
}
#endif
CheckCdrom();
// Auto-detect: get region first, then rcnt-bios reset
SysReset(1);
if (file[0] != '\0') {
Load(file);
} else {
if (runcd == RUN_CD) {
if (LoadCdrom() == -1) {
ReleasePlugins();
printf(_("Could not load CD-ROM!\n"));
return -1;
}
}
}
// If a state has been specified, then load that
if (loadst) {
StatesC = loadst - 1;
gchar *state_filename = get_state_filename(StatesC);
LoadState(state_filename);
g_free(state_filename);
}
psxCpu->Execute();
}
return 0;
}
#endif
int SysInit() {
#ifdef EMU_LOG
#ifndef LOG_STDOUT
emuLog = fopen("emuLog.txt","wb");
#else
emuLog = stdout;
#endif
setvbuf(emuLog, NULL, _IONBF, 0);
#endif
if (EmuInit() == -1) {
printf(_("PSX emulator couldn't be initialized.\n"));
return -1;
}
LoadMcds(Config.Mcd1, Config.Mcd2); /* TODO Do we need to have this here, or in the calling main() function?? */
if (Config.Debug) {
StartDebugger();
}
return 0;
}
static void dummy_lace()
{
}
void SysReset() {
// rearmed hack: EmuReset() runs some code when real BIOS is used,
// but we usually do reset from menu while GPU is not open yet,
// so we need to prevent updateLace() call..
void *real_lace = GPUupdateLace;
GPU_updateLace = dummy_lace;
EmuReset();
// hmh core forgets this
CDR_stop();
GPU_updateLace = real_lace;
}
void SysClose() {
EmuShutdown();
ReleasePlugins();
StopDebugger();
if (emuLog != NULL) fclose(emuLog);
}
void SysPrintf(const char *fmt, ...) {
#if 0
va_list list;
char msg[512];
va_start(list, fmt);
vsprintf(msg, fmt, list);
va_end(list);
if (Config.PsxOut) {
static char linestart = 1;
int l = strlen(msg);
printf(linestart ? " * %s" : "%s", msg);
if (l > 0 && msg[l - 1] == '\n') {
linestart = 1;
} else {
linestart = 0;
}
}
#ifdef EMU_LOG
#ifndef LOG_STDOUT
fprintf(emuLog, "%s", msg);
#endif
#endif
#endif
}
void SysMessage(const char *fmt, ...) {
#if 0
va_list list;
char msg[512];
va_start(list, fmt);
vsprintf(msg, fmt, list);
va_end(list);
if (Config.PsxOut) {
static char linestart = 1;
int l = strlen(msg);
printf(linestart ? " * %s" : "%s", msg);
if (l > 0 && msg[l - 1] == '\n') {
linestart = 1;
} else {
linestart = 0;
}
}
#ifdef EMU_LOG
#ifndef LOG_STDOUT
fprintf(emuLog, "%s", msg);
#endif
#endif
#endif
}
void *SysLoadLibrary(const char *lib) {
return dlopen(lib, RTLD_NOW);
}
void *SysLoadSym(void *lib, const char *sym) {
return dlsym(lib, sym);
}
const char *SysLibError() {
return dlerror();
}
void SysCloseLibrary(void *lib) {
dlclose(lib);
}
static void SysDisableScreenSaver() {
#if 0
static time_t fake_key_timer = 0;
static char first_time = 1, has_test_ext = 0, t = 1;
Display *display;
extern unsigned long gpuDisp;
display = (Display *)gpuDisp;
if (first_time) {
// check if xtest is available
int a, b, c, d;
has_test_ext = XTestQueryExtension(display, &a, &b, &c, &d);
first_time = 0;
}
if (has_test_ext && fake_key_timer < time(NULL)) {
XTestFakeRelativeMotionEvent(display, t *= -1, 0, 0);
fake_key_timer = time(NULL) + 55;
}
#endif
}
void SysUpdate() {
#if 0
PADhandleKey(PAD1_keypressed());
PADhandleKey(PAD2_keypressed());
SysDisableScreenSaver();
#endif
}
/* ADB TODO Replace RunGui() with StartGui ()*/
void SysRunGui() {
#if 0
StartGui();
#endif
}
| 8,954 |
C
|
.c
| 325 | 24.698462 | 113 | 0.666589 |
tirolino99/libpsx
| 2 | 12 | 0 |
GPL-2.0
|
9/7/2024, 2:31:37 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,678,651 |
cfg.c
|
tirolino99_libpsx/project/jni/libpcsxcore/video/cfg.c
|
/***************************************************************************
cfg.c - description
-------------------
begin : Sun Oct 28 2001
copyright : (C) 2001 by Pete Bernert
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. See also the license.txt file for *
* additional informations. *
* *
***************************************************************************/
#define _IN_CFG
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#undef FALSE
#undef TRUE
#define MAKELONG(low,high) ((unsigned long)(((unsigned short)(low)) | (((unsigned long)((unsigned short)(high))) << 16)))
#include "externals.h"
#include "cfg.h"
#include "gpu.h"
char * pConfigFile = NULL;
// CONFIG FILE helpers....
// some helper macros:
#define GetValue(name, var) \
p = strstr(pB, name); \
if (p != NULL) { \
p+=strlen(name); \
while ((*p == ' ') || (*p == '=')) p++; \
if (*p != '\n') var = atoi(p); \
}
#define GetFloatValue(name, var) \
p = strstr(pB, name); \
if (p != NULL) { \
p+=strlen(name); \
while ((*p == ' ') || (*p == '=')) p++; \
if (*p != '\n') var = (float)atof(p); \
}
#define SetValue(name, var) \
p = strstr(pB, name); \
if (p != NULL) { \
p+=strlen(name); \
while ((*p == ' ') || (*p == '=')) p++; \
if (*p != '\n') { \
len = sprintf(t1, "%d", var); \
strncpy(p, t1, len); \
if (p[len] != ' ' && p[len] != '\n' && p[len] != 0) p[len] = ' '; \
} \
} \
else { \
size+=sprintf(pB+size, "%s = %d\n", name, var); \
}
#define SetFloatValue(name, var) \
p = strstr(pB, name); \
if (p != NULL) { \
p+=strlen(name); \
while ((*p == ' ') || (*p == '=')) p++; \
if (*p != '\n') { \
len = sprintf(t1, "%.1f", (double)var); \
strncpy(p, t1, len); \
if (p[len] != ' ' && p[len] != '\n' && p[len] != 0) p[len] = ' '; \
} \
} \
else { \
size+=sprintf(pB+size, "%s = %.1f\n", name, (double)var); \
}
void gpuReadConfigFile()
{
struct stat buf;
FILE *in;char t[256];int len, size;
char * pB, * p;
if(pConfigFile)
strcpy(t,pConfigFile);
else
{
strcpy(t,"dfxvideo.cfg");
in = fopen(t,"rb");
if (!in)
{
strcpy(t,"cfg/dfxvideo.cfg");
in = fopen(t,"rb");
if(!in) sprintf(t,"%s/.pcsx/plugins/dfxvideo.cfg",getenv("HOME"));
else fclose(in);
}
else fclose(in);
}
if (stat(t, &buf) == -1) return;
size = buf.st_size;
in = fopen(t,"rb");
if (!in) return;
pB=(char *)malloc(size + 1);
memset(pB,0,size + 1);
len = fread(pB, 1, size, in);
fclose(in);
GetValue("ResX", iResX);
if(iResX<20) iResX=20;
iResX=(iResX/4)*4;
GetValue("ResY", iResY);
if(iResY<20) iResY=20;
iResY=(iResY/4)*4;
iWinSize=MAKELONG(iResX,iResY);
GetValue("NoStretch", iUseNoStretchBlt);
GetValue("Dithering", iUseDither);
GetValue("FullScreen", iWindowMode);
if(iWindowMode!=0) iWindowMode=0;
else iWindowMode=1;
GetValue("ShowFPS", iShowFPS);
if(iShowFPS<0) iShowFPS=0;
if(iShowFPS>1) iShowFPS=1;
GetValue("Maintain43", iMaintainAspect);
if(iMaintainAspect<0) iMaintainAspect=0;
if(iMaintainAspect>1) iMaintainAspect=1;
GetValue("UseFrameLimit", UseFrameLimit);
if(UseFrameLimit<0) UseFrameLimit=0;
if(UseFrameLimit>1) UseFrameLimit=1;
GetValue("UseFrameSkip", UseFrameSkip);
if(UseFrameSkip<0) UseFrameSkip=0;
if(UseFrameSkip>1) UseFrameSkip=1;
GetValue("FPSDetection", iFrameLimit);
if(iFrameLimit<1) iFrameLimit=1;
if(iFrameLimit>2) iFrameLimit=2;
GetFloatValue("FrameRate", fFrameRate);
fFrameRate/=10;
if(fFrameRate<10.0f) fFrameRate=10.0f;
if(fFrameRate>1000.0f) fFrameRate=1000.0f;
GetValue("CfgFixes", dwCfgFixes);
GetValue("UseFixes", iUseFixes);
if(iUseFixes<0) iUseFixes=0;
if(iUseFixes>1) iUseFixes=1;
free(pB);
}
void ExecCfg(char *arg) {
#if 0
char cfg[256];
struct stat buf;
strcpy(cfg, "./cfgDFXVideo");
if (stat(cfg, &buf) != -1) {
if (fork() == 0) {
execl(cfg, "cfgDFXVideo", arg, NULL);
exit(0);
}
return;
}
strcpy(cfg, "./cfg/cfgDFXVideo");
if (stat(cfg, &buf) != -1) {
if (fork() == 0) {
execl(cfg, "cfgDFXVideo", arg, NULL);
exit(0);
}
return;
}
sprintf(cfg, "%s/.pcsx/plugins/cfg/cfgDFXVideo", getenv("HOME"));
if (stat(cfg, &buf) != -1) {
if (fork() == 0) {
execl(cfg, "cfgDFXVideo", arg, NULL);
exit(0);
}
return;
}
printf("ERROR: cfgDFXVideo file not found!\n");
#endif
}
void SoftDlgProc(void)
{
ExecCfg("CFG");
}
void AboutDlgProc(void)
{
char args[256];
sprintf(args, "ABOUT");
ExecCfg(args);
}
void gpuReadConfig(void)
{
// defaults
iResX=320;iResY=240;
iWinSize=MAKELONG(iResX,iResY);
iColDepth=16;
iWindowMode=1;
iMaintainAspect=1;
UseFrameLimit=1;
UseFrameSkip=1;
iFrameLimit=2;
fFrameRate=200.0f;
dwCfgFixes=0;
iUseFixes=0;
iUseNoStretchBlt=0;
iUseDither=0;
iShowFPS=0;
// read sets
//gpuReadConfigFile();
// additional checks
if(!iColDepth) iColDepth=32;
if(iUseFixes) dwActFixes=dwCfgFixes;
SetFixes();
}
void WriteConfig(void) {
#if 0
struct stat buf;
FILE *out;char t[256];int len, size;
char * pB, * p; char t1[8];
if(pConfigFile)
strcpy(t,pConfigFile);
else
{
strcpy(t,"dfxvideo.cfg");
out = fopen(t,"rb");
if (!out)
{
strcpy(t,"cfg/dfxvideo.cfg");
out = fopen(t,"rb");
if(!out) sprintf(t,"%s/.pcsx/plugins/dfxvideo.cfg",getenv("HOME"));
else fclose(out);
}
else fclose(out);
}
if (stat(t, &buf) != -1) size = buf.st_size;
else size = 0;
out = fopen(t,"rb");
if (!out) {
// defaults
iResX=640;iResY=480;
iColDepth=32;
iWindowMode=1;
iMaintainAspect=0;
UseFrameLimit=0;
UseFrameSkip=0;
iFrameLimit=2;
fFrameRate=200.0f;
dwCfgFixes=0;
iUseFixes=0;
iUseNoStretchBlt=0;
iUseDither=0;
iShowFPS=0;
size = 0;
pB=(char *)malloc(4096);
memset(pB,0,4096);
}
else {
pB=(char *)malloc(size+4096);
memset(pB,0,size+4096);
len = fread(pB, 1, size, out);
fclose(out);
}
SetValue("ResX", iResX);
SetValue("ResY", iResY);
SetValue("NoStretch", iUseNoStretchBlt);
SetValue("Dithering", iUseDither);
SetValue("FullScreen", !iWindowMode);
SetValue("ShowFPS", iShowFPS);
SetValue("Maintain43", iMaintainAspect);
SetValue("UseFrameLimit", UseFrameLimit);
SetValue("UseFrameSkip", UseFrameSkip);
SetValue("FPSDetection", iFrameLimit);
SetFloatValue("FrameRate", fFrameRate);
SetValue("CfgFixes", (unsigned int)dwCfgFixes);
SetValue("UseFixes", iUseFixes);
out = fopen(t,"wb");
if (!out) return;
len = fwrite(pB, 1, size, out);
fclose(out);
free(pB);
#endif
}
| 7,212 |
C
|
.c
| 269 | 23.98513 | 125 | 0.581773 |
tirolino99/libpsx
| 2 | 12 | 0 |
GPL-2.0
|
9/7/2024, 2:31:37 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,678,660 |
new_dynarec.h
|
tirolino99_libpsx/project/jni/libpcsxcore/new_dynarec/new_dynarec.h
|
#define NEW_DYNAREC 1
extern int pcaddr;
extern int pending_exception;
extern int stop;
void new_dynarec_init();
void new_dynarec_cleanup();
void new_dynarec_clear_full();
void new_dyna_start();
void invalidate_all_pages();
void invalidate_block(unsigned int block);
| 270 |
C
|
.c
| 10 | 25.7 | 42 | 0.797665 |
tirolino99/libpsx
| 2 | 12 | 0 |
GPL-2.0
|
9/7/2024, 2:31:37 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,678,662 |
minimal.c
|
tirolino99_libpsx/project/jni/libpcsxcore/android/minimal.c
|
#include "minimal.h"
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>
#include <sys/time.h>
#include <sys/resource.h>
#define X_RES emu_screen_w
#define Y_RES emu_screen_h
#define BITS_PER_PIXEL emu_screen_bpp
#define NUM_BITS_PER_BYTE 8
extern void setScreenSize(int width, int height);
unsigned int emu_screen_w = 320;
unsigned int emu_screen_h = 240;
unsigned int emu_screen_bpp = 16;
unsigned int emu_screen_pitch = 320 * 2;
int updateAspect = 0;
extern u32 get_key_states();
#if 0
u16 screen[1024*1024];
#endif
/* The font is generated from Xorg 6x10-L1.bdf */
static unsigned char gp2x_fontf[256][10] = {
{ 0x00>>2, 0xA8>>2, 0x00>>2, 0x88>>2, 0x00>>2, 0x88>>2, 0x00>>2, 0xA8>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x20>>2, 0x70>>2, 0xF8>>2, 0x70>>2, 0x20>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0xA8>>2, 0x54>>2, 0xA8>>2, 0x54>>2, 0xA8>>2, 0x54>>2, 0xA8>>2, 0x54>>2, 0xA8>>2, 0x54>>2, },
{ 0x00>>2, 0x90>>2, 0x90>>2, 0xF0>>2, 0x90>>2, 0x90>>2, 0x78>>2, 0x10>>2, 0x10>>2, 0x10>>2, },
{ 0x00>>2, 0xE0>>2, 0x80>>2, 0xC0>>2, 0x80>>2, 0xB8>>2, 0x20>>2, 0x30>>2, 0x20>>2, 0x20>>2, },
{ 0x00>>2, 0x70>>2, 0x80>>2, 0x80>>2, 0x70>>2, 0x70>>2, 0x48>>2, 0x70>>2, 0x48>>2, 0x48>>2, },
{ 0x00>>2, 0x80>>2, 0x80>>2, 0x80>>2, 0xF0>>2, 0x78>>2, 0x40>>2, 0x70>>2, 0x40>>2, 0x40>>2, },
{ 0x00>>2, 0x20>>2, 0x50>>2, 0x20>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x20>>2, 0x20>>2, 0xF8>>2, 0x20>>2, 0x20>>2, 0xF8>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x90>>2, 0xD0>>2, 0xD0>>2, 0xB0>>2, 0x90>>2, 0x40>>2, 0x40>>2, 0x40>>2, 0x78>>2, },
{ 0x00>>2, 0x90>>2, 0x90>>2, 0x60>>2, 0x40>>2, 0x78>>2, 0x10>>2, 0x10>>2, 0x10>>2, 0x10>>2, },
{ 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0xE0>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0xE0>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x3C>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, },
{ 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x3C>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0xFC>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, },
{ 0xFC>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0xFC>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0xFF>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0xFC>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0xFC>>2, },
{ 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x3C>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, },
{ 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0xE0>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, },
{ 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0xFC>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0xFC>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, },
{ 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, },
{ 0x00>>2, 0x18>>2, 0x60>>2, 0x80>>2, 0x60>>2, 0x18>>2, 0x00>>2, 0xF8>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0xC0>>2, 0x30>>2, 0x08>>2, 0x30>>2, 0xC0>>2, 0x00>>2, 0xF8>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0xF8>>2, 0x50>>2, 0x50>>2, 0x50>>2, 0x50>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x08>>2, 0x10>>2, 0xF8>>2, 0x20>>2, 0xF8>>2, 0x40>>2, 0x80>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x30>>2, 0x48>>2, 0x40>>2, 0xE0>>2, 0x40>>2, 0x48>>2, 0xB0>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x20>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x00>>2, 0x20>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x50>>2, 0x50>>2, 0x50>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x50>>2, 0x50>>2, 0xF8>>2, 0x50>>2, 0xF8>>2, 0x50>>2, 0x50>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x20>>2, 0x70>>2, 0xA0>>2, 0x70>>2, 0x28>>2, 0x70>>2, 0x20>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x48>>2, 0xA8>>2, 0x50>>2, 0x20>>2, 0x50>>2, 0xA8>>2, 0x90>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x40>>2, 0xA0>>2, 0xA0>>2, 0x40>>2, 0xA8>>2, 0x90>>2, 0x68>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x10>>2, 0x20>>2, 0x40>>2, 0x40>>2, 0x40>>2, 0x20>>2, 0x10>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x40>>2, 0x20>>2, 0x10>>2, 0x10>>2, 0x10>>2, 0x20>>2, 0x40>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x88>>2, 0x50>>2, 0xF8>>2, 0x50>>2, 0x88>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x20>>2, 0x20>>2, 0xF8>>2, 0x20>>2, 0x20>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x30>>2, 0x20>>2, 0x40>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0xF8>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x20>>2, 0x70>>2, 0x20>>2, 0x00>>2, },
{ 0x00>>2, 0x08>>2, 0x08>>2, 0x10>>2, 0x20>>2, 0x40>>2, 0x80>>2, 0x80>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x20>>2, 0x50>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x50>>2, 0x20>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x20>>2, 0x60>>2, 0xA0>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0xF8>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x70>>2, 0x88>>2, 0x08>>2, 0x30>>2, 0x40>>2, 0x80>>2, 0xF8>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0xF8>>2, 0x08>>2, 0x10>>2, 0x30>>2, 0x08>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x10>>2, 0x30>>2, 0x50>>2, 0x90>>2, 0xF8>>2, 0x10>>2, 0x10>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0xF8>>2, 0x80>>2, 0xB0>>2, 0xC8>>2, 0x08>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x30>>2, 0x40>>2, 0x80>>2, 0xB0>>2, 0xC8>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0xF8>>2, 0x08>>2, 0x10>>2, 0x10>>2, 0x20>>2, 0x40>>2, 0x40>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x70>>2, 0x88>>2, 0x98>>2, 0x68>>2, 0x08>>2, 0x10>>2, 0x60>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x20>>2, 0x70>>2, 0x20>>2, 0x00>>2, 0x20>>2, 0x70>>2, 0x20>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x20>>2, 0x70>>2, 0x20>>2, 0x00>>2, 0x30>>2, 0x20>>2, 0x40>>2, 0x00>>2, },
{ 0x00>>2, 0x08>>2, 0x10>>2, 0x20>>2, 0x40>>2, 0x20>>2, 0x10>>2, 0x08>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0xF8>>2, 0x00>>2, 0xF8>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x40>>2, 0x20>>2, 0x10>>2, 0x08>>2, 0x10>>2, 0x20>>2, 0x40>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x70>>2, 0x88>>2, 0x10>>2, 0x20>>2, 0x20>>2, 0x00>>2, 0x20>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x70>>2, 0x88>>2, 0x98>>2, 0xA8>>2, 0xB0>>2, 0x80>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x20>>2, 0x50>>2, 0x88>>2, 0x88>>2, 0xF8>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0xF0>>2, 0x48>>2, 0x48>>2, 0x70>>2, 0x48>>2, 0x48>>2, 0xF0>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x70>>2, 0x88>>2, 0x80>>2, 0x80>>2, 0x80>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0xF0>>2, 0x48>>2, 0x48>>2, 0x48>>2, 0x48>>2, 0x48>>2, 0xF0>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0xF8>>2, 0x80>>2, 0x80>>2, 0xF0>>2, 0x80>>2, 0x80>>2, 0xF8>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0xF8>>2, 0x80>>2, 0x80>>2, 0xF0>>2, 0x80>>2, 0x80>>2, 0x80>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x70>>2, 0x88>>2, 0x80>>2, 0x80>>2, 0x98>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0xF8>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x70>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x38>>2, 0x10>>2, 0x10>>2, 0x10>>2, 0x10>>2, 0x90>>2, 0x60>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x88>>2, 0x90>>2, 0xA0>>2, 0xC0>>2, 0xA0>>2, 0x90>>2, 0x88>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x80>>2, 0x80>>2, 0x80>>2, 0x80>>2, 0x80>>2, 0x80>>2, 0xF8>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x88>>2, 0x88>>2, 0xD8>>2, 0xA8>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x88>>2, 0x88>>2, 0xC8>>2, 0xA8>>2, 0x98>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0xF0>>2, 0x88>>2, 0x88>>2, 0xF0>>2, 0x80>>2, 0x80>>2, 0x80>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0xA8>>2, 0x70>>2, 0x08>>2, 0x00>>2, },
{ 0x00>>2, 0xF0>>2, 0x88>>2, 0x88>>2, 0xF0>>2, 0xA0>>2, 0x90>>2, 0x88>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x70>>2, 0x88>>2, 0x80>>2, 0x70>>2, 0x08>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0xF8>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x50>>2, 0x50>>2, 0x50>>2, 0x20>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0xA8>>2, 0xA8>>2, 0xD8>>2, 0x88>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x88>>2, 0x88>>2, 0x50>>2, 0x20>>2, 0x50>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x88>>2, 0x88>>2, 0x50>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0xF8>>2, 0x08>>2, 0x10>>2, 0x20>>2, 0x40>>2, 0x80>>2, 0xF8>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x70>>2, 0x40>>2, 0x40>>2, 0x40>>2, 0x40>>2, 0x40>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x80>>2, 0x80>>2, 0x40>>2, 0x20>>2, 0x10>>2, 0x08>>2, 0x08>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x70>>2, 0x10>>2, 0x10>>2, 0x10>>2, 0x10>>2, 0x10>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x20>>2, 0x50>>2, 0x88>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0xF8>>2, 0x00>>2, },
{ 0x20>>2, 0x10>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x70>>2, 0x08>>2, 0x78>>2, 0x88>>2, 0x78>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x80>>2, 0x80>>2, 0xB0>>2, 0xC8>>2, 0x88>>2, 0xC8>>2, 0xB0>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0x80>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x08>>2, 0x08>>2, 0x68>>2, 0x98>>2, 0x88>>2, 0x98>>2, 0x68>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0xF8>>2, 0x80>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x30>>2, 0x48>>2, 0x40>>2, 0xF0>>2, 0x40>>2, 0x40>>2, 0x40>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x78>>2, 0x88>>2, 0x88>>2, 0x78>>2, 0x08>>2, 0x88>>2, 0x70>>2, },
{ 0x00>>2, 0x80>>2, 0x80>>2, 0xB0>>2, 0xC8>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x20>>2, 0x00>>2, 0x60>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x08>>2, 0x00>>2, 0x18>>2, 0x08>>2, 0x08>>2, 0x08>>2, 0x48>>2, 0x48>>2, 0x30>>2, },
{ 0x00>>2, 0x80>>2, 0x80>>2, 0x88>>2, 0x90>>2, 0xE0>>2, 0x90>>2, 0x88>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x60>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0xD0>>2, 0xA8>>2, 0xA8>>2, 0xA8>>2, 0x88>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0xB0>>2, 0xC8>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0xB0>>2, 0xC8>>2, 0x88>>2, 0xC8>>2, 0xB0>>2, 0x80>>2, 0x80>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x68>>2, 0x98>>2, 0x88>>2, 0x98>>2, 0x68>>2, 0x08>>2, 0x08>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0xB0>>2, 0xC8>>2, 0x80>>2, 0x80>>2, 0x80>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x70>>2, 0x80>>2, 0x70>>2, 0x08>>2, 0xF0>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x40>>2, 0x40>>2, 0xF0>>2, 0x40>>2, 0x40>>2, 0x48>>2, 0x30>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x98>>2, 0x68>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x88>>2, 0x88>>2, 0x50>>2, 0x50>>2, 0x20>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x88>>2, 0x88>>2, 0xA8>>2, 0xA8>>2, 0x50>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x88>>2, 0x50>>2, 0x20>>2, 0x50>>2, 0x88>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x88>>2, 0x88>>2, 0x98>>2, 0x68>>2, 0x08>>2, 0x88>>2, 0x70>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0xF8>>2, 0x10>>2, 0x20>>2, 0x40>>2, 0xF8>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x18>>2, 0x20>>2, 0x10>>2, 0x60>>2, 0x10>>2, 0x20>>2, 0x18>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x60>>2, 0x10>>2, 0x20>>2, 0x18>>2, 0x20>>2, 0x10>>2, 0x60>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x48>>2, 0xA8>>2, 0x90>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x20>>2, 0x00>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x20>>2, 0x78>>2, 0xA0>>2, 0xA0>>2, 0xA0>>2, 0x78>>2, 0x20>>2, 0x00>>2, },
{ 0x00>>2, 0x30>>2, 0x48>>2, 0x40>>2, 0xE0>>2, 0x40>>2, 0x48>>2, 0xB0>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x88>>2, 0x70>>2, 0x50>>2, 0x70>>2, 0x88>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x88>>2, 0x88>>2, 0x50>>2, 0x20>>2, 0xF8>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x00>>2, },
{ 0x00>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x00>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x70>>2, 0x80>>2, 0xE0>>2, 0x90>>2, 0x48>>2, 0x38>>2, 0x08>>2, 0x70>>2, 0x00>>2, },
{ 0x50>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x70>>2, 0x88>>2, 0xA8>>2, 0xC8>>2, 0xA8>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x38>>2, 0x48>>2, 0x58>>2, 0x28>>2, 0x00>>2, 0x78>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x24>>2, 0x48>>2, 0x90>>2, 0x48>>2, 0x24>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x78>>2, 0x08>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x78>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x70>>2, 0x88>>2, 0xE8>>2, 0xC8>>2, 0xC8>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0xF8>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x20>>2, 0x50>>2, 0x20>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x20>>2, 0x20>>2, 0xF8>>2, 0x20>>2, 0x20>>2, 0xF8>>2, 0x00>>2, 0x00>>2, },
{ 0x30>>2, 0x48>>2, 0x10>>2, 0x20>>2, 0x78>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x70>>2, 0x08>>2, 0x30>>2, 0x08>>2, 0x70>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x10>>2, 0x20>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0xC8>>2, 0xB0>>2, 0x80>>2, 0x00>>2, },
{ 0x00>>2, 0x78>>2, 0xE8>>2, 0xE8>>2, 0x68>>2, 0x28>>2, 0x28>>2, 0x28>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x20>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x10>>2, 0x20>>2, },
{ 0x20>>2, 0x60>>2, 0x20>>2, 0x20>>2, 0x70>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x30>>2, 0x48>>2, 0x48>>2, 0x30>>2, 0x00>>2, 0x78>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x90>>2, 0x48>>2, 0x24>>2, 0x48>>2, 0x90>>2, 0x00>>2, 0x00>>2, },
{ 0x40>>2, 0xC0>>2, 0x40>>2, 0x40>>2, 0xE4>>2, 0x0C>>2, 0x14>>2, 0x3C>>2, 0x04>>2, 0x00>>2, },
{ 0x40>>2, 0xC0>>2, 0x40>>2, 0x40>>2, 0xE8>>2, 0x14>>2, 0x04>>2, 0x08>>2, 0x1C>>2, 0x00>>2, },
{ 0xC0>>2, 0x20>>2, 0x40>>2, 0x20>>2, 0xC8>>2, 0x18>>2, 0x28>>2, 0x78>>2, 0x08>>2, 0x00>>2, },
{ 0x00>>2, 0x20>>2, 0x00>>2, 0x20>>2, 0x20>>2, 0x40>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x40>>2, 0x20>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0xF8>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, },
{ 0x10>>2, 0x20>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0xF8>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, },
{ 0x20>>2, 0x50>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0xF8>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, },
{ 0x48>>2, 0xB0>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0xF8>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, },
{ 0x50>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0xF8>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, },
{ 0x20>>2, 0x50>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0xF8>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x3C>>2, 0x50>>2, 0x90>>2, 0x9C>>2, 0xF0>>2, 0x90>>2, 0x9C>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x70>>2, 0x88>>2, 0x80>>2, 0x80>>2, 0x80>>2, 0x88>>2, 0x70>>2, 0x20>>2, 0x40>>2, },
{ 0x40>>2, 0xF8>>2, 0x80>>2, 0x80>>2, 0xF0>>2, 0x80>>2, 0x80>>2, 0xF8>>2, 0x00>>2, 0x00>>2, },
{ 0x10>>2, 0xF8>>2, 0x80>>2, 0x80>>2, 0xF0>>2, 0x80>>2, 0x80>>2, 0xF8>>2, 0x00>>2, 0x00>>2, },
{ 0x20>>2, 0xF8>>2, 0x80>>2, 0x80>>2, 0xF0>>2, 0x80>>2, 0x80>>2, 0xF8>>2, 0x00>>2, 0x00>>2, },
{ 0x50>>2, 0xF8>>2, 0x80>>2, 0x80>>2, 0xF0>>2, 0x80>>2, 0x80>>2, 0xF8>>2, 0x00>>2, 0x00>>2, },
{ 0x40>>2, 0x20>>2, 0x70>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x10>>2, 0x20>>2, 0x70>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x20>>2, 0x50>>2, 0x70>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x50>>2, 0x00>>2, 0x70>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0xF0>>2, 0x48>>2, 0x48>>2, 0xE8>>2, 0x48>>2, 0x48>>2, 0xF0>>2, 0x00>>2, 0x00>>2, },
{ 0x28>>2, 0x50>>2, 0x88>>2, 0xC8>>2, 0xA8>>2, 0x98>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, },
{ 0x40>>2, 0x20>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x10>>2, 0x20>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x20>>2, 0x50>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x28>>2, 0x50>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x50>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x88>>2, 0x50>>2, 0x20>>2, 0x50>>2, 0x88>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x70>>2, 0x98>>2, 0x98>>2, 0xA8>>2, 0xC8>>2, 0xC8>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x40>>2, 0x20>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x10>>2, 0x20>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x20>>2, 0x50>>2, 0x00>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x50>>2, 0x00>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x10>>2, 0x20>>2, 0x88>>2, 0x88>>2, 0x50>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x80>>2, 0xF0>>2, 0x88>>2, 0xF0>>2, 0x80>>2, 0x80>>2, 0x80>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x70>>2, 0x88>>2, 0x90>>2, 0xA0>>2, 0x90>>2, 0x88>>2, 0xB0>>2, 0x00>>2, 0x00>>2, },
{ 0x40>>2, 0x20>>2, 0x00>>2, 0x70>>2, 0x08>>2, 0x78>>2, 0x88>>2, 0x78>>2, 0x00>>2, 0x00>>2, },
{ 0x10>>2, 0x20>>2, 0x00>>2, 0x70>>2, 0x08>>2, 0x78>>2, 0x88>>2, 0x78>>2, 0x00>>2, 0x00>>2, },
{ 0x20>>2, 0x50>>2, 0x00>>2, 0x70>>2, 0x08>>2, 0x78>>2, 0x88>>2, 0x78>>2, 0x00>>2, 0x00>>2, },
{ 0x28>>2, 0x50>>2, 0x00>>2, 0x70>>2, 0x08>>2, 0x78>>2, 0x88>>2, 0x78>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x50>>2, 0x00>>2, 0x70>>2, 0x08>>2, 0x78>>2, 0x88>>2, 0x78>>2, 0x00>>2, 0x00>>2, },
{ 0x20>>2, 0x50>>2, 0x20>>2, 0x70>>2, 0x08>>2, 0x78>>2, 0x88>>2, 0x78>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x78>>2, 0x14>>2, 0x7C>>2, 0x90>>2, 0x7C>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0x80>>2, 0x88>>2, 0x70>>2, 0x20>>2, 0x40>>2, },
{ 0x40>>2, 0x20>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0xF8>>2, 0x80>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x10>>2, 0x20>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0xF8>>2, 0x80>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x20>>2, 0x50>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0xF8>>2, 0x80>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x50>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0xF8>>2, 0x80>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x40>>2, 0x20>>2, 0x00>>2, 0x60>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x20>>2, 0x40>>2, 0x00>>2, 0x60>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x20>>2, 0x50>>2, 0x00>>2, 0x60>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x50>>2, 0x00>>2, 0x60>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0xC0>>2, 0x30>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x28>>2, 0x50>>2, 0x00>>2, 0xB0>>2, 0xC8>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, },
{ 0x40>>2, 0x20>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x10>>2, 0x20>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x20>>2, 0x50>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x28>>2, 0x50>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x50>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x20>>2, 0x00>>2, 0xF8>>2, 0x00>>2, 0x20>>2, 0x00>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x00>>2, 0x00>>2, 0x78>>2, 0x98>>2, 0xA8>>2, 0xC8>>2, 0xF0>>2, 0x00>>2, 0x00>>2, },
{ 0x40>>2, 0x20>>2, 0x00>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x98>>2, 0x68>>2, 0x00>>2, 0x00>>2, },
{ 0x10>>2, 0x20>>2, 0x00>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x98>>2, 0x68>>2, 0x00>>2, 0x00>>2, },
{ 0x20>>2, 0x50>>2, 0x00>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x98>>2, 0x68>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x50>>2, 0x00>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x98>>2, 0x68>>2, 0x00>>2, 0x00>>2, },
{ 0x00>>2, 0x10>>2, 0x20>>2, 0x88>>2, 0x88>>2, 0x98>>2, 0x68>>2, 0x08>>2, 0x88>>2, 0x70>>2, },
{ 0x00>>2, 0x00>>2, 0x80>>2, 0xF0>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0xF0>>2, 0x80>>2, 0x80>>2, },
{ 0x00>>2, 0x50>>2, 0x00>>2, 0x88>>2, 0x88>>2, 0x98>>2, 0x68>>2, 0x08>>2, 0x88>>2, 0x70>>2, },
};
static gp2x_font gp2x_default_font;
void (*gp2x_printfchar)(gp2x_font *f, unsigned char c);
void gp2x_printfchar32(gp2x_font *f, unsigned char c)
{
unsigned long *dst=&((unsigned long*)gp2x_screen16)[f->x+f->y*emu_screen_w],w,h=f->h;
unsigned char *src=&f->data[c*10];
if(f->solid)
while(h--)
{
w=f->wmask;
while(w)
{
if( *src & w ) *dst++=f->fg; else *dst++=f->bg;
w>>=1;
}
src++;
dst+=emu_screen_w-(f->w);
}
else
while(h--)
{
w=f->wmask;
while(w)
{
if( *src & w ) *dst=f->fg;
dst++;
w>>=1;
}
src++;
dst+=emu_screen_w-(f->w);
}
}
void gp2x_printfchar16(gp2x_font *f, unsigned char c)
{
unsigned short *dst=&((unsigned short*)gp2x_screen16)[f->x+f->y*emu_screen_w],w,h=f->h;
//unsigned char *src=f->data[ (c%16)*f->w + (c/16)*f->h ];
unsigned char *src=&f->data[c*10];
if(f->solid)
while(h--)
{
w=f->wmask;
while(w)
{
if( *src & w ) *dst++=f->fg; else *dst++=f->bg;
w>>=1;
}
src++;
dst+=emu_screen_w-(f->w);
}
else
while(h--)
{
w=f->wmask;
while(w)
{
if( *src & w ) *dst=f->fg;
dst++;
w>>=1;
}
src++;
dst+=emu_screen_w-(f->w);
}
}
void gp2x_printf(gp2x_font *f, int x, int y, const char *format, ...)
{
char buffer[4096]; int c; gp2x_font *g=&gp2x_default_font;
va_list args;
va_start(args, format);
vsprintf(buffer, format, args);
if(f!=NULL) g=f;
if(x<0) x=g->x; else g->x=x;
if(y<0) y=g->y; else g->y=y;
for(c=0;buffer[c];c++)
{
switch(buffer[c])
{
case '\b': g->x=x;g->y=y; break;
case '\n': g->y+=g->h;
case '\r': g->x=x;
break;
default: gp2x_printfchar(g, (unsigned char)buffer[c]);
g->x+=g->w;
break;
}
}
//gp2x_video_flip_single();
}
unsigned long gp2x_joystick_read(void)
{
return get_key_states();
}
void gp2x_init(int ticks_per_second, int bpp, int rate, int bits, int stereo, int hz, int solid_font)
{
emu_screen_w = 320;
emu_screen_h = 240;
emu_screen_bpp = 16;
emu_screen_pitch = 320 * 2;
gp2x_video_RGB_clearscreen16();
//init font
gp2x_printfchar = gp2x_printfchar16;
gp2x_default_font.x = gp2x_default_font.y = 0;
gp2x_default_font.wmask = 1<<(6-1);
gp2x_default_font.w = 6;
gp2x_default_font.h = 10;
gp2x_default_font.data = (unsigned char*)gp2x_fontf;
gp2x_default_font.fg = 0xFFFF;
gp2x_default_font.bg = 0x0000;
gp2x_default_font.solid = solid_font;
//atexit(gp2x_deinit);
//if( setpriority(PRIO_PROCESS, 0, -20) != 0 )
//{
// gp2x_printf(NULL, 20, 0, "ERROR: MUST BE A SUPER USER TO SET PRIORITY");
// gp2x_timer_delay(100000);
//}
}
void gp2x_change_res(int w, int h, int bpp)
{
emu_screen_w = w;
emu_screen_h = h;
emu_screen_bpp = bpp;
emu_screen_pitch = w * (bpp/8);
gp2x_printfchar = gp2x_printfchar16; // bpp == 16 ? gp2x_printfchar16 : gp2x_printfchar32;
gp2x_default_font.fg = 0xFFFF; //bpp == 16 ? 0xFFFF : 0xFFFFFFFF;
gp2x_default_font.bg = 0x0; //bpp == 16 ? 0x0 : 0xFF000000;
setScreenSize(w, h);
}
void gp2x_deinit(void)
{
}
void gp2x_video_RGB_clearscreen16(void)
{
memset(gp2x_screen16, 0, emu_screen_pitch*emu_screen_h);
}
u64 gp2x_timer_read(void)
{
struct timeval current_time;
gettimeofday(¤t_time, NULL);
return (u64)((u64)(current_time.tv_sec * 1000) + (u64)(current_time.tv_usec / 1000));
}
unsigned long timeGetTime()
{
struct timeval tv;
gettimeofday(&tv, 0); // well, maybe there are better ways
return tv.tv_sec * 1000 + tv.tv_usec/1000; // to do that, but at least it works
}
| 29,348 |
C
|
.c
| 429 | 65.062937 | 102 | 0.534929 |
tirolino99/libpsx
| 2 | 12 | 0 |
GPL-2.0
|
9/7/2024, 2:31:37 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,678,666 |
iphone.c
|
tirolino99_libpsx/project/jni/libpcsxcore/sound/iphone.c
|
#include "spu.h"
#include "externals.h"
#include "../minimal.h"
u32 last_ticks;
#define AUDIO_BUFFERS 12
#define AUDIO_BUFFER_SIZE (NSSIZE*2)
/*
static pthread_mutex_t sound_mutex;
static pthread_cond_t sound_cond;
*/
//static unsigned char sound_buffer[AUDIO_BUFFERS][AUDIO_BUFFER_SIZE];
static int sound_buffer_index = 0;
extern void *MAINThread(void *arg);
/* Start Sound Core */
void SetupSound(void)
{
#ifndef NOSOUND
if( enable_audio == 0 ) return;
sound_buffer_index = 0;
last_ticks = 0;
/*
memset(sound_buffer, 0, AUDIO_BUFFER_SIZE*AUDIO_BUFFERS);
pthread_mutex_init(&sound_mutex, NULL);
pthread_cond_init(&sound_cond, NULL);
*/
demuteSound();
#endif
}
/* Stop Sound Core */
void RemoveSound(void)
{
#ifndef NOSOUND
if( enable_audio == 0 ) return;
/*
pthread_cond_signal(&sound_cond);
*/ muteSound();
/*
pthread_cond_signal(&sound_cond);
usleep(100000);
pthread_cond_destroy(&sound_cond);
pthread_mutex_destroy(&sound_mutex);
*/
#endif
}
void renderSound(unsigned char* stream, int len, int index)
{
#ifndef NOSOUND
if( enable_audio == 0 ) return;
if(!bEndThread)
{
/*
struct timespec tspec;
tspec.tv_sec = 0;
tspec.tv_nsec = 900000000; // 1000000000 / (44100 / (45 * 2 * 2)) / 1.25
pthread_mutex_lock(&sound_mutex);
pthread_cond_timedwait(&sound_cond, &sound_mutex, &tspec);
pthread_mutex_unlock(&sound_mutex);
*/
MAINThread(0);
memcpy(stream, pSpuBuffer, (len < (AUDIO_BUFFER_SIZE) ? len : (AUDIO_BUFFER_SIZE)));
//memcpy(stream, sound_buffer[index], (len < (AUDIO_BUFFER_SIZE) ? len : (AUDIO_BUFFER_SIZE)));
}
#endif
}
/* Feed Sound Data */
void SoundFeedStreamData(unsigned char* pSound,long lBytes)
{
#ifndef NOSOUND
#if 0
if( enable_audio == 0 ) return;
if(pSound == NULL || lBytes <= 0)
return;
memcpy(sound_buffer[sound_buffer_index], pSound, (lBytes > (AUDIO_BUFFER_SIZE) ? (AUDIO_BUFFER_SIZE) : lBytes));
sound_buffer_index++;
if(sound_buffer_index >= AUDIO_BUFFERS)
{
sound_buffer_index = 0;
}
#endif
/*
pthread_cond_signal(&sound_cond);
*/
#endif
}
unsigned long SoundGetBytesBuffered(void)
{
if( enable_audio == 0 ) return TESTSIZE+1;
if(last_ticks == 0)
{
last_ticks = timeGetTime_spu();
}
if(timeGetTime_spu() >= last_ticks + 2)
{
last_ticks = timeGetTime_spu();
return 0;
}
return TESTSIZE+1;
}
| 2,364 |
C
|
.c
| 98 | 21.653061 | 114 | 0.696997 |
tirolino99/libpsx
| 2 | 12 | 0 |
GPL-2.0
|
9/7/2024, 2:31:37 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,678,674 |
android.c
|
tirolino99_libpsx/project/jni/libpcsxcore/sound/android.c
|
#include "spu.h"
#include "externals.h"
#include "../minimal.h"
#ifndef NOSOUND
extern void render_audio(s16 *data, u32 size);
extern void start_audio();
extern void end_audio();
extern int is_paused();
#endif
u32 last_ticks;
u32 last_render_ticks;
static pthread_mutex_t sound_mutex;
static pthread_cond_t sound_cond;
pthread_t sound_thread=0;
volatile int sound_thread_exit=0;
unsigned int sound_buffer_bytes = 0;
unsigned int sound_new_buffer = 0;
static void *sound_thread_play(void *none);
static unsigned char sound_buffer[32768];
static unsigned char sound_buffer_silence[32768];
/* Start Sound Core */
void SetupSound(void)
{
#ifndef NOSOUND
if( enable_audio == 0 ) return;
#if 0
last_ticks = 0;
last_render_ticks = 0;
#endif
#if 0
sound_buffer_bytes = 0;
sound_new_buffer = 0;
sound_thread_exit = 0;
pthread_create( &sound_thread, NULL, sound_thread_play, NULL);
#else
memset(sound_buffer_silence, 0, 882 * 2);
#endif
#endif
}
/* Stop Sound Core */
void RemoveSound(void)
{
#ifndef NOSOUND
if( enable_audio == 0 ) return;
#if 0
sound_thread_exit = 1;
pthread_cond_signal(&sound_cond);
#endif
#endif
}
static void *sound_thread_play(void *none)
{
#ifndef NOSOUND
#if 0
if( enable_audio == 0 ) return NULL;
pthread_mutex_init(&sound_mutex, NULL);
pthread_cond_init(&sound_cond, NULL);
start_audio();
while(!sound_thread_exit && !bEndThread)
{
pthread_mutex_lock(&sound_mutex);
pthread_cond_wait(&sound_cond, &sound_mutex);
pthread_mutex_unlock(&sound_mutex);
if(pSpuBuffer)
render_audio((s16*)pSpuBuffer, sound_buffer_bytes);
}
sound_thread_exit = 0;
pthread_cond_destroy(&sound_cond);
pthread_mutex_destroy(&sound_mutex);
end_audio();
#endif
return NULL;
#endif
}
void CheckPauseSound()
{
while(is_paused() && bEndThread == 0)
{
usleep(20000);
render_audio((s16*)sound_buffer_silence, 882 * 2);
}
}
/* Feed Sound Data */
void SoundFeedStreamData(unsigned char* pSound,long lBytes)
{
#ifndef NOSOUND
//u32 render_ticks;
if( enable_audio == 0 ) return;
if(pSound == NULL || lBytes <= 0 || lBytes > 32768) // || sound_new_buffer != 0)
return;
//memcpy(sound_buffer, pSound, lBytes);
//sound_buffer_bytes = lBytes;
//pthread_cond_signal(&sound_cond);
render_audio((s16*)pSound, lBytes);
#if 0
if(last_render_ticks == 0)
{
last_render_ticks = timeGetTime_spu();
}
render_ticks = timeGetTime_spu();
if(render_ticks < last_render_ticks + 5)
{
u32 render_delta = (last_render_ticks + 5) - render_ticks;
if(render_delta < 5)
{
usleep(render_delta * 1000);
}
}
last_render_ticks = timeGetTime_spu();
#endif
#endif
}
unsigned long SoundGetBytesBuffered(void)
{
if( enable_audio == 0 ) return TESTSIZE+1;
if(last_ticks == 0)
{
last_ticks = timeGetTime_spu();
}
if(timeGetTime_spu() >= last_ticks + 2)
{
last_ticks = timeGetTime_spu();
return 0;
}
return TESTSIZE+1;
}
| 2,930 |
C
|
.c
| 126 | 20.936508 | 82 | 0.706115 |
tirolino99/libpsx
| 2 | 12 | 0 |
GPL-2.0
|
9/7/2024, 2:31:37 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,678,704 |
gte_neon.h
|
tirolino99_libpsx/project/jni/libpcsxcore/gte_neon.h
|
void gteRTPS_neon(void *cp2_regs, int opcode);
void gteRTPT_neon(void *cp2_regs, int opcode);
void gteMVMVA_neon(void *cp2_regs, int opcode);
void gteNCLIP_neon(void *cp2_regs, int opcode);
| 190 |
C
|
.h
| 4 | 46.5 | 47 | 0.763441 |
tirolino99/libpsx
| 2 | 12 | 0 |
GPL-2.0
|
9/7/2024, 2:31:37 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,678,721 |
minimal.h
|
tirolino99_libpsx/project/jni/libpcsxcore/minimal.h
|
#ifndef __ROOT_MINIMAL_H__
#define __ROOT_MINIMAL_H__
#ifdef ANDROID
// Include path issues
#include "android/minimal.h"
#elif defined(IPHONE)
#include "iphone/minimal.h"
#else
#include "minimal.h"
#endif
#endif
| 213 |
C
|
.h
| 11 | 18.272727 | 28 | 0.766169 |
tirolino99/libpsx
| 2 | 12 | 0 |
GPL-2.0
|
9/7/2024, 2:31:37 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,678,735 |
config.h
|
tirolino99_libpsx/project/jni/libpcsxcore/config.h
|
//
// Copyright (c) 2008, Wei Mingzhi. All rights reserved.
//
// Use, redistribution and modification of this code is unrestricted as long as this
// notice is preserved.
//
#ifndef CONFIG_H
#define CONFIG_H
#ifndef MAXPATHLEN
#define MAXPATHLEN 1024
#endif
#ifndef PACKAGE_VERSION
#define PACKAGE_VERSION "1.3"
#endif
#ifndef PREFIX
#define PREFIX "./"
#endif
#ifndef inline
#ifdef _DEBUG
#define inline /* */
#else
#define inline __inline__
#endif
#endif
#endif
| 471 |
C
|
.h
| 25 | 17.6 | 84 | 0.772727 |
tirolino99/libpsx
| 2 | 12 | 0 |
GPL-2.0
|
9/7/2024, 2:31:37 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,678,784 |
raster.h
|
tirolino99_libpsx/project/jni/libpcsxcore/gpuAPI/newGPU/raster.h
|
#ifndef RASTER_H
#define RASTER_H
///////////////////////////////////////////////////////////////////////////////
// GPU Render Primitives
// Images
void gpuLoadImage (void);
void gpuStoreImage (void);
void gpuMoveImage (void);
void gpuClearImage (void);
// Lines
void gpuDrawLF(void);
void gpuDrawLG(void);
// Sprite
void gpuDrawS(void);
void gpuDrawT(void);
// Poligon
void gpuDrawF3 ();
void gpuDrawFT3();
void gpuDrawG3 ();
void gpuDrawGT3();
///////////////////////////////////////////////////////////////////////////////
// GPU Raster Macros
#define GPU_RGB16(rgb) ((((rgb)&0xF80000)>>9)|(((rgb)&0xF800)>>6)|(((rgb)&0xF8)>>3))
#define GPU_EXPANDSIGN_POLY(x) (((s32)(x)<<20)>>20)
#define GPU_EXPANDSIGN_SPRT(x) (((s32)(x)<<21)>>21)
#define GPU_TESTRANGE(x) { if((u32)(x+1024) > 2047) return; }
#define GPU_SWAP(a,b,t) {(t)=(a);(a)=(b);(b)=(t);}
///////////////////////////////////////////////////////////////////////////////
#endif //RASTER_H
| 1,030 |
C
|
.h
| 29 | 32.758621 | 92 | 0.480082 |
tirolino99/libpsx
| 2 | 12 | 0 |
GPL-2.0
|
9/7/2024, 2:31:37 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,690 |
common.c
|
dterweij_ndjbdns/common.c
|
/*
* common.c: This file is part of the `djbdns' project, originally written
* by Dr. D J Bernstein and later released under public-domain since late
* December 2007 (http://cr.yp.to/distributors.html).
*
* Copyright (C) 2009 - 2015 Prasad J Pandit
*
* This program is a free software; you can redistribute it and/or modify
* it under the terms of GNU General Public License as published by Free
* Software Foundation; either version 2 of the license or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* of FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#define _GNU_SOURCE
#include <err.h>
#include <time.h>
#include <ctype.h>
#include <stdio.h>
#include <fcntl.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <netinet/in.h>
#include "taia.h"
#include "uint32.h"
#define free(ptr) free ((ptr)); (ptr) = NULL
extern short mode, debug_level;
uint32 seed[32];
int seedpos = 0;
void
seed_adduint32 (uint32 u)
{
int i = 0;
seed[seedpos] += u;
if (++seedpos == 32)
{
for (i = 0; i < 32; ++i)
{
u = ((u ^ seed[i]) + 0x9e3779b9) ^ (u << 7) ^ (u >> 25);
seed[i] = u;
}
seedpos = 0;
}
}
void
seed_addtime (void)
{
int i = 0;
struct taia t;
char tpack[TAIA_PACK];
taia_now (&t);
taia_pack (tpack, &t);
for (i = 0; i < TAIA_PACK; ++i)
seed_adduint32 (tpack[i]);
}
/*
* strtrim: removes leading & trailing white spaces(space, tab, new-line, etc)
* from a given character string and returns a pointer to the new string.
* Do free(3) it later.
*/
char *
strtrim (const char *s)
{
if (s == NULL)
return NULL;
const char *e = &s[strlen(s) - 1];
while (*s)
{
if (isspace (*s))
s++;
else
break;
}
while (*e)
{
if (isspace (*e))
e--;
else
break;
}
e++;
return strndup (s, e - s);
}
/* checks if the given variable is valid & used by dnscache. */
int
check_variable (const char *var)
{
assert (var != NULL);
int i = 0, l = 0;
const char *known_variable[] = \
{
"AXFR", "DATALIMIT", "CACHESIZE", "IP", "IPSEND",
"UID", "GID", "ROOT", "HIDETTL", "FORWARDONLY",
"MERGEQUERIES", "DEBUG_LEVEL", "BASE", "TCPREMOTEIP",
"TCPREMOTEPORT"
};
l = sizeof (known_variable) / sizeof (*known_variable);
for (i = 0; i < l; i++)
{
if (strlen (var) != strlen (known_variable[i]))
continue;
if (!memcmp (var, known_variable[i], strlen (var)))
return 1;
}
return 0;
}
void
read_conf (const char *file)
{
assert (file != NULL);
int lcount = 0;
FILE *fp = NULL;
size_t l = 0, n = 0;
char *line = NULL, *key = NULL, *val = NULL;
if (!(fp = fopen (file, "r")))
err (-1, "could not open file `%s'", file);
while ((signed)(n = getline (&line, &l, fp)) != -1)
{
lcount++;
line[n - 1] = '\0';
char *s = strtrim (line);
if (*s && *s != '#' && *s != '\n')
{
key = strtrim (strtok (s, "="));
if (!check_variable (key))
errx (-1, "%s: %d: unknown variable `%s'", file, lcount, key);
val = strtrim (strtok (NULL, "="));
if (debug_level)
warnx ("%s: %s", key, val);
if (val)
{
setenv (key, val, 1);
free (val);
}
free (s);
free (key);
free (line);
}
seed_addtime ();
}
if (line)
free (line);
fclose (fp);
}
/*
* redirect stdout & stderr to a log file. flag parameter decides which
* descriptors to redirect; It is an 'OR' of STDOUT_FILENO & STDERR_FILENO.
*/
void
redirect_to_log (const char *logfile, unsigned char flag)
{
assert (logfile != NULL);
int fd = 0, perm = S_IRUSR | S_IWUSR;
if ((fd = open (logfile, O_CREAT | O_WRONLY | O_APPEND, perm)) == -1)
err (-1, "could not open logfile `%s'", logfile);
if (flag & STDOUT_FILENO && dup2 (fd, STDOUT_FILENO) == -1)
err (-1, "could not duplicate stdout");
if (flag & STDERR_FILENO && dup2 (fd, STDERR_FILENO) == -1)
err (-1, "could not duplicate stderr");
}
/*
* wirets pid to a file under /var/run directory, which will be used by
* /sbin/service to shut down the dns daemon.
*/
void
write_pid (const char *pidfile)
{
int n = 0, fd = 0, perm = 0;
char *pid = strdup (pidfile);
perm = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
if ((fd = open (pid, O_CREAT | O_WRONLY | O_TRUNC, perm)) == -1)
err (-1, "could not open file: `%s'", pid);
memset (pid, '\0', strlen (pid));
n = sprintf (pid, "%d\n", getpid ());
write (fd, pid, n);
close (fd);
free (pid);
}
void
handle_term (int n)
{
warnx ("going down with signal: %d ---\n", n);
exit (0);
}
/* gettimezone: reads local timezone definition from '/etc/localtime'
* and returns a pointer to a POSIX TZ environment variable string or
* NULL in case of an error; See: tzfile(5), tzset(3).
*
* std offset dst [offset],start[/time],end[/time]
*
* Ex: TZ="NZST-12:00:00NZDT-13:00:00,M10.1.0,M3.3.0"
*/
char *
gettimezone (void)
{
#define TZ_VERSION '2'
#define TZ_MAGIC "TZif"
#define TZ_FILE "/etc/localtime"
int32_t fd = 0;
char *tz = NULL;
struct stat st;
char *tzbuf = NULL;
if ((fd = open (TZ_FILE, O_RDONLY | O_NDELAY)) < 0)
{
warn ("could not access timezone: %s", TZ_FILE);
return tz;
}
if (fstat (fd, &st) < 0)
err (-1, "could not get file status: %s", TZ_FILE);
tzbuf = mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (tzbuf == MAP_FAILED)
err (-1, "could not mmap(2) file: %s", TZ_FILE);
if (memcmp (tzbuf, TZ_MAGIC, 4))
err (-1, "invalid timezone file: %s, see tzfile(5)", TZ_FILE);
if (TZ_VERSION == *(tzbuf + 4) || TZ_VERSION == *(tzbuf + 4) - 1)
{
char *p1 = NULL, *p2 = NULL;
p1 = p2 = tzbuf + st.st_size - 1;
while (*--p1 != '\n');
if (!(tz = calloc (abs (p2 - p1), sizeof (char))))
err (-1, "could not allocate memory for tz");
memcpy (tz, p1 + 1, abs (p2 - p1) - 1);
}
munmap (tzbuf, st.st_size);
close (fd);
return tz;
}
/*
* set_timezone: set `TZ' environment variable to appropriate time zone value.
* `TZ' environment variable is used by numerous - <time.h> - functions to
* perform local time conversions. TZ: NAME[+-]HH:MM:SS[DST]
* ex: IST-5:30:00, EST+5:00:00EDT etc.
*/
void
set_timezone (void)
{
char *tzone = getenv ("TZ");
if (tzone)
return;
tzone = gettimezone ();
if (!tzone)
{
time_t t;
struct tm *tt = NULL;
char hh = 0, mm = 0, ss = 0;
t = time (NULL);
tt = localtime (&t);
hh = timezone / (60 * 60);
mm = abs (timezone % (60 * 60) / 60);
ss = abs (timezone % (60 * 60) % 60);
if (!(tzone = calloc (22, sizeof (char))))
err (-1, "could not allocate memory for tzone");
snprintf (tzone, 22, "%s%+02d:%02d:%02d%s", tzname[0],
hh, mm, ss, (tt->tm_isdst > 0) ? tzname[1] : "");
}
setenv ("TZ", tzone, 1);
free (tzone);
}
| 7,853 |
C
|
.c
| 269 | 23.881041 | 78 | 0.560823 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,701 |
dnsip.c
|
dterweij_ndjbdns/dnsip.c
|
/*
* dnsip.c: This file is part of the `djbdns' project, originally written
* by Dr. D J Bernstein and later released under public-domain since late
* December 2007 (http://cr.yp.to/distributors.html).
*
* Copyright (C) 2009 - 2012 Prasad J Pandit
*
* This program is a free software; you can redistribute it and/or modify
* it under the terms of GNU General Public License as published by Free
* Software Foundation; either version 2 of the license or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* of FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include "version.h"
#include "ip4.h"
#include "dns.h"
#include "strerr.h"
#include "buffer.h"
char str[IP4_FMT];
static stralloc out;
static stralloc fqdn;
static char seed[128];
short mode = 0;
static char *prog = NULL;
enum output_mode { OLD = 0, NEW = 1 };
void
usage (void)
{
printf ("Usage: %s <domain-name> [<domain-name> ...]\n", prog);
}
void
printh (void)
{
usage ();
printf ("\n Options:\n");
printf ("%-17s %s\n", " -h --help", "print this help");
printf ("%-17s %s\n", " -n --new", "use new output style");
printf ("%-17s %s\n", " -v --version", "print version information");
printf ("\nReport bugs to <[email protected]>\n");
}
int
check_option (int argc, char *argv[])
{
int n = 0, ind = 0;
const char optstr[] = "+:hnv";
struct option lopt[] = \
{
{ "help", no_argument, NULL, 'h' },
{ "new", no_argument, NULL, 'n' },
{ "version", no_argument, NULL, 'v' },
{ 0, 0, 0, 0 }
};
if (argc < 2)
{
usage ();
exit (0);
}
opterr = optind = 0;
while ((n = getopt_long (argc, argv, optstr, lopt, &ind)) != -1)
{
switch (n)
{
case 'h':
printh ();
exit (0);
case 'n':
mode = NEW;
break;
case 'v':
printf ("%s is part of djbdns version %s\n", prog, VERSION);
exit (0);
default:
errx (-1, "unknown option `%c', see: --help", optopt);
}
}
return optind;
}
int
main (int argc, char *argv[])
{
int i = 0;
char *x = NULL;
prog = strdup ((x = strrchr (argv[0], '/')) != NULL ? x + 1 : argv[0]);
i = check_option (argc, argv);
argv += i;
argc -= i;
dns_random_init (seed);
while (*argv)
{
if (!stralloc_copys (&fqdn, *argv))
err (-1, "could not allocate enough memory");
if (dns_ip4 (&out, &fqdn) == -1)
errx (-1, "could not find IP address for `%s'", *argv);
if (mode & NEW)
{
buffer_puts (buffer_1, *argv);
buffer_puts (buffer_1, ": ");
}
for (i = 0; (unsigned)i + 4 <= out.len; i += 4)
{
buffer_put (buffer_1, str, ip4_fmt (str, out.s + i));
buffer_puts (buffer_1, " ");
}
buffer_puts (buffer_1, "\n");
++argv;
}
buffer_flush (buffer_1);
return 0;
}
| 3,514 |
C
|
.c
| 122 | 23.622951 | 78 | 0.572404 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,710 |
ip4_fmt.c
|
dterweij_ndjbdns/ip4_fmt.c
|
/*
* ip4_fmt.c: This file is part of the `djbdns' project, originally written
* by Dr. D J Bernstein and later released under public-domain since late
* December 2007 (http://cr.yp.to/distributors.html).
*
* Copyright (C) 2009 - 2013 Prasad J Pandit
*
* This program is a free software; you can redistribute it and/or modify
* it under the terms of GNU General Public License as published by Free
* Software Foundation; either version 2 of the license or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* of FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "fmt.h"
#include "ip4.h"
unsigned int
ip4_fmt (char *s, const char ip[4])
{
unsigned int i = 0, j = 0, len = 0;
while (j < 4)
{
i = fmt_ulong (s, (unsigned long)(unsigned char)ip[j++]);
len += i;
if (s)
s += i;
if (j == 4)
break;
if (s)
*s++ = '.';
++len;
}
return len;
}
| 1,355 |
C
|
.c
| 41 | 28.926829 | 78 | 0.664122 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,716 |
server.c
|
dterweij_ndjbdns/server.c
|
/*
* server.c: This file is part of the `djbdns' project, originally written
* by Dr. D J Bernstein and later released under public-domain since late
* December 2007 (http://cr.yp.to/distributors.html).
*
* Copyright (C) 2009 - 2014 Prasad J Pandit
*
* This program is a free software; you can redistribute it and/or modify
* it under the terms of GNU General Public License as published by Free
* Software Foundation; either version 2 of the license or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* of FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <err.h>
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <signal.h>
#include <getopt.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/resource.h>
#include "version.h"
#include "env.h"
#include "ip4.h"
#include "dns.h"
#include "log.h"
#include "byte.h"
#include "case.h"
#include "buffer.h"
#include "strerr.h"
#include "uint16.h"
#include "ndelay.h"
#include "socket.h"
#include "common.h"
#include "iopause.h"
#include "droproot.h"
#include "response.h"
extern void initialize (void);
extern int respond (char *, char *, char *);
static char ip[4];
static uint16 port;
static uint16 server_port = 53;
static int len;
static char *q;
static char buf[1024];
static char *prog = NULL;
short mode = 0, debug_level = 0;
char *cfgfile = NULL, *logfile = NULL, *pidfile = NULL;
void
usage (void)
{
printf ("Usage: %s [OPTIONS]\n", prog);
}
void
printh (void)
{
usage ();
printf ("\n Options: \n");
printf ("%-17s %s\n", " -c <value>", "specify path to config file");
printf ("%-17s %s\n", " -d <value>", "print debug messages");
printf ("%-17s %s\n", " -D", "start server as daemon");
printf ("%-17s %s\n", " -l <value>", "specify path to log file");
printf ("%-17s %s\n", " -p <value>", "specify path to pid file");
printf ("%-17s %s\n", " -P <value>", "specify server port, default: 53");
printf ("\n");
printf ("%-17s %s\n", " -h --help", "print this help");
printf ("%-17s %s\n", " -v --version", "print version information");
printf ("\nReport bugs to <[email protected]>\n");
}
int
check_option (int argc, char *argv[])
{
int n = 0, ind = 0;
const char optstr[] = "+:c:d:Dl:p:P:hv";
struct option lopt[] = \
{
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'v' },
{ 0, 0, 0, 0 }
};
opterr = optind = mode = 0;
while ((n = getopt_long (argc, argv, optstr, lopt, &ind)) != -1)
{
switch (n)
{
case 'c':
cfgfile = strdup (optarg);
break;
case 'd':
mode |= DEBUG;
debug_level = atoi (optarg);
break;
case 'D':
mode |= DAEMON;
break;
case 'l':
logfile = strdup (optarg);
break;
case 'p':
pidfile = strdup (optarg);
break;
case 'P':
server_port = atoi (optarg);
break;
case 'h':
printh ();
exit (0);
case 'v':
printf ("%s version %s\n", prog, VERSION);
exit (0);
case ':':
errx (-1, "option `%c' takes an argument, see: --help", optopt);
default:
errx (-1, "unknown option `%c', see: --help", optopt);
}
}
return optind;
}
static unsigned long long qnum = 0;
static int
doit (void)
{
char qtype[2];
char qclass[2];
char header[12];
unsigned int pos = 0;
if ((unsigned)len >= sizeof buf)
goto NOQ;
if (!(pos = dns_packet_copy (buf, len, 0, header, 12)))
goto NOQ;
if (header[2] & 128)
goto NOQ;
if (header[4])
goto NOQ;
if (header[5] != 1)
goto NOQ;
if (!(pos = dns_packet_getname (buf, len, pos, &q)))
goto NOQ;
if (!(pos = dns_packet_copy (buf, len, pos, qtype, 2)))
goto NOQ;
if (!(pos = dns_packet_copy (buf, len, pos, qclass, 2)))
goto NOQ;
if (!response_query (q, qtype, qclass))
goto NOQ;
response_id (header);
qnum++;
if (byte_equal (qclass, 2, DNS_C_IN))
response[2] |= 4;
else if (byte_diff (qclass, 2, DNS_C_ANY))
goto WEIRDCLASS;
response[3] &= ~128;
if (!(header[2] & 1))
response[2] &= ~1;
if (header[2] & 126)
goto NOTIMP;
if (byte_equal (qtype, 2, DNS_T_AXFR))
goto NOTIMP;
case_lowerb (q, dns_domain_length (q));
if (!respond (q, qtype, ip))
{
log_query (qnum, ip, port, header, q, qtype);
return 0;
}
log_query (qnum, ip, port, header, q, qtype);
return 1;
NOTIMP:
response[3] &= ~15;
response[3] |= 4;
log_query (qnum, ip, port, header, q, qtype);
return 1;
WEIRDCLASS:
response[3] &= ~15;
response[3] |= 1;
log_query (qnum, ip, port, header, q, qtype);
return 1;
NOQ:
log_query (qnum, ip, port, "\0\0", "", "\0\0");
return 0;
}
int
main (int argc, char *argv[])
{
time_t t = 0;
char *x = NULL;
struct sigaction sa;
iopause_fd *iop = NULL;
int i = 0, n = 0, *udp53 = NULL;
prog = strdup ((x = strrchr (argv[0], '/')) != NULL ? x + 1 : argv[0]);
sa.sa_handler = handle_term;
sigaction (SIGINT, &sa, NULL);
sigaction (SIGTERM, &sa, NULL);
sa.sa_handler = SIG_IGN;
sigaction (SIGPIPE, &sa, NULL);
i = check_option (argc, argv);
argc -= i;
argv += i;
if (mode & DAEMON)
{
i = fork ();
if (i == -1)
err (-1, "could not fork a daemon process");
if (i > 0)
return 0;
}
time (&t);
memset (buf, 0, sizeof (buf));
strftime (buf, sizeof (buf), "%b-%d %Y %T %Z", localtime (&t));
warnx ("version %s: starting: %s\n", VERSION, buf);
set_timezone ();
if (debug_level)
warnx ("TIMEZONE: %s", env_get ("TZ"));
initialize ();
if (!debug_level)
if ((x = env_get ("DEBUG_LEVEL")))
debug_level = atol (x);
warnx ("DEBUG_LEVEL set to `%d'", debug_level);
#ifndef __CYGWIN__
if ((x = env_get ("DATALIMIT")))
{
struct rlimit r;
unsigned long dlimit = atol (x);
if (getrlimit (RLIMIT_DATA, &r) != 0)
err (-1, "could not get resource RLIMIT_DATA");
r.rlim_cur = (dlimit <= r.rlim_max) ? dlimit : r.rlim_max;
if (setrlimit (RLIMIT_DATA, &r) != 0)
err (-1, "could not set resource RLIMIT_DATA");
if (debug_level)
warnx ("DATALIMIT set to `%ld' bytes", r.rlim_cur);
}
#endif
if (!(x = env_get ("IP")))
err (-1, "$IP not set");
for (i = 0; (unsigned)i < strlen (x); i++)
n = (x[i] == ',') ? n+1 : n;
if (!(udp53 = calloc (n+1, sizeof (int))))
err (-1, "could not allocate enough memory for udp53");
if (!(iop = calloc (n+1, sizeof (iopause_fd))))
err (-1, "could not allocate enough memory for iop");
i = n = 0;
while (x[i])
{
unsigned int l = 0;
if (!(l = ip4_scan(x+i, ip)))
errx (-1, "could not parse IP address `%s'", x + i);
udp53[n] = socket_udp();
if (udp53[n] == -1)
errx (-1, "could not open UDP socket");
if (socket_bind4_reuse (udp53[n], ip, server_port) == -1)
errx (-1, "could not bind UDP socket");
ndelay_off (udp53[n]);
socket_tryreservein (udp53[n], 65536);
iop[n].fd = udp53[n];
iop[n].events = IOPAUSE_READ;
n++;
i += (x[i + l] == ',') ? l + 1 : l;
}
droproot ();
while (1)
{
struct taia stamp;
struct in_addr odst; /* original destination IP */
struct taia deadline;
taia_now (&stamp);
taia_uint (&deadline, 300);
taia_add (&deadline, &deadline, &stamp);
iopause (iop, n, &deadline, &stamp);
for (i = 0; i < n; i++)
{
if (!iop[i].revents)
continue;
len = socket_recv4 (udp53[i], buf, sizeof (buf), ip, &port, &odst);
if (len < 0)
continue;
if (!doit ())
continue;
if (response_len > 512)
response_tc ();
/* may block for buffer space; if it fails, too bad */
len = socket_send4 (udp53[i], response,
response_len, ip, port, &odst);
if (len < 0)
continue;
if (debug_level > 1)
log_querydone(qnum, response, response_len);
}
}
return 0;
}
| 9,116 |
C
|
.c
| 299 | 24.09699 | 79 | 0.543357 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,723 |
tinydns.c
|
dterweij_ndjbdns/tinydns.c
|
/*
* tinydns.c: This file is part of the `djbdns' project, originally written
* by Dr. D J Bernstein and later released under public-domain since late
* December 2007 (http://cr.yp.to/distributors.html).
*
* Copyright (C) 2009 - 2014 Prasad J Pandit
*
* This program is a free software; you can redistribute it and/or modify
* it under the terms of GNU General Public License as published by Free
* Software Foundation; either version 2 of the license or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* of FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <unistd.h>
#include "dns.h"
#include "common.h"
#define PIDFILE "/var/run/tinydns.pid"
#define LOGFILE "/var/log/tinydns.log"
#define CFGFILE SYSCONFDIR"/ndjbdns/tinydns.conf"
extern short mode;
static char seed[128];
extern char *cfgfile, *logfile, *pidfile;
void
initialize (void)
{
cfgfile = cfgfile ? cfgfile : CFGFILE;
logfile = logfile ? logfile : LOGFILE;
pidfile = pidfile ? pidfile : PIDFILE;
read_conf (cfgfile);
if (mode & DAEMON)
{
/* redirect stdout & stderr to a log file */
redirect_to_log (logfile, STDOUT_FILENO | STDERR_FILENO);
write_pid (pidfile);
}
dns_random_init (seed);
}
| 1,634 |
C
|
.c
| 45 | 33.466667 | 78 | 0.729456 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,740 |
ip4_scan.c
|
dterweij_ndjbdns/ip4_scan.c
|
/*
* ip4_scan.c: This file is part of the `djbdns' project, originally
* written by Dr. D J Bernstein and later released under public-domain since
* late December 2007 (http://cr.yp.to/distributors.html).
*
* Copyright (C) 2009 - 2013 Prasad J Pandit
*
* This program is a free software; you can redistribute it and/or modify
* it under the terms of GNU General Public License as published by Free
* Software Foundation; either version 2 of the license or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* of FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "ip4.h"
#include "scan.h"
unsigned int
ip4_scan (const char *s, char ip[4])
{
unsigned long u = 0;
unsigned int i = 0, j = 0, len = 0;
while (j < 4)
{
i = scan_ulong (s, &u);
if (!i)
return 0;
ip[j++] = u;
s += i;
len += i;
if (j == 4)
break;
if (*s != '.')
return 0;
++s;
++len;
}
return len;
}
| 1,409 |
C
|
.c
| 45 | 26.822222 | 78 | 0.647535 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,749 |
dnsfilter.c
|
dterweij_ndjbdns/dnsfilter.c
|
/*
* dnsfilter.c: This file is part of the `djbdns' project, originally written
* by Dr. D J Bernstein and later released under public-domain since late
* December 2007 (http://cr.yp.to/distributors.html).
*
* Copyright (C) 2009 - 2012 Prasad J Pandit
*
* This program is a free software; you can redistribute it and/or modify
* it under the terms of GNU General Public License as published by Free
* Software Foundation; either version 2 of the license or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* of FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <unistd.h>
#include "version.h"
#include "strerr.h"
#include "buffer.h"
#include "stralloc.h"
#include "alloc.h"
#include "dns.h"
#include "ip4.h"
#include "byte.h"
#include "scan.h"
#include "taia.h"
#include "iopause.h"
#include "error.h"
short mode = 0;
static char *prog = NULL;
struct line
{
stralloc left;
stralloc middle;
stralloc right;
struct dns_transmit dt;
int flagactive;
iopause_fd *io;
} *x;
struct line tmp;
unsigned int xnum = 0;
unsigned int xmax = 1000;
unsigned int numactive = 0;
unsigned int maxactive = 10;
static stralloc partial;
int flag0 = 1;
char inbuf[1024];
unsigned int inbuflen = 0;
int iolen = 0;
iopause_fd *io;
iopause_fd *inio;
char ip[4];
char servers[64];
char name[DNS_NAME4_DOMAIN];
void
usage (void)
{
printf ("Usage: %s [OPTIONS]\n", prog);
}
void
printh (void)
{
usage ();
printf ("\n Options:\n");
printf ("%-17s %s\n", " -c <N>", "do N queries in parallel");
printf ("%-17s %s\n", " -h --help", "print this help");
printf ("%-17s %s\n", " -l <N>", "read ahead at most N lines");
printf ("%-17s %s\n", " -v --version", "print version information");
printf ("\nReport bugs to <[email protected]>\n");
}
int
check_option (int argc, char *argv[])
{
int n = 0, ind = 0;
const char optstr[] = "+:c:hl:v";
struct option lopt[] = \
{
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'v' },
{ 0, 0, 0, 0 }
};
opterr = optind = 0;
while ((n = getopt_long (argc, argv, optstr, lopt, &ind)) != -1)
{
switch (n)
{
case 'c':
maxactive = atoi (optarg);
if (maxactive < 1)
maxactive = 1;
if (maxactive > 1000)
maxactive = 1000;
break;
case 'h':
printh ();
exit (0);
case 'l':
xmax = atoi (optarg);
if (xmax < 1)
xmax = 1;
if (xmax > 1000000)
xmax = 1000000;
break;
case 'v':
printf ("%s is part of djbdns version %s\n", prog, VERSION);
exit (0);
default:
errx (-1, "unknown option `%c', see: --help", optopt);
}
}
return optind;
}
void
errout (int i)
{
int j = 0;
if (!stralloc_copys (&x[i].middle, ":"))
err (-1, "could not allocate enough memory");
if (!stralloc_cats (&x[i].middle, error_str (errno)))
err (-1, "could not allocate enough memory");
for (j = 0; (unsigned)j < x[i].middle.len; j++)
if (x[i].middle.s[j] == ' ')
x[i].middle.s[j] = '-';
}
int
main (int argc, char *argv[])
{
char *t = NULL;
int i = 0, j = 0, r = 0;
struct taia stamp;
struct taia deadline;
prog = strdup ((t = strrchr (argv[0], '/')) != NULL ? t + 1 : argv[0]);
i = check_option (argc, argv);
argv += i;
argc -= i;
x = (struct line *) alloc (xmax * sizeof (struct line));
if (!x)
err (-1, "could not allocate enough memory");
io = (iopause_fd *) alloc ((xmax + 1) * sizeof (iopause_fd));
if (!io)
err (-1, "could not allocate enough memory");
if (!stralloc_copys (&partial, ""))
err (-1, "could not allocate enough memory");
while (flag0 || inbuflen || partial.len || xnum)
{
taia_now (&stamp);
taia_uint (&deadline, 120);
taia_add (&deadline, &deadline, &stamp);
iolen = 0;
if (flag0)
{
if (inbuflen < sizeof inbuf)
{
inio = io + iolen++;
inio->fd = 0;
inio->events = IOPAUSE_READ;
}
}
for (i = 0; (unsigned)i < xnum; ++i)
{
if (x[i].flagactive)
{
x[i].io = io + iolen++;
dns_transmit_io (&x[i].dt, x[i].io, &deadline);
}
}
iopause (io, iolen, &deadline, &stamp);
if (flag0)
{
if (inbuflen < sizeof inbuf)
{
if (inio->revents)
{
r = read (0, inbuf + inbuflen, (sizeof inbuf) - inbuflen);
if (r <= 0)
flag0 = 0;
else
inbuflen += r;
}
}
}
for (i = 0; (unsigned)i < xnum;++i)
{
if (x[i].flagactive)
{
r = dns_transmit_get (&x[i].dt, x[i].io, &stamp);
if (r == -1)
{
errout (i);
x[i].flagactive = 0;
--numactive;
}
else if (r == 1)
{
if (dns_name_packet (&x[i].middle, x[i].dt.packet,
x[i].dt.packetlen) == -1)
errout (i);
if (x[i].middle.len)
{
if (!stralloc_cats(&x[i].left,"="))
err (-1, "could not allocate enough memory");
}
x[i].flagactive = 0;
--numactive;
}
}
}
for (;;)
{
if (xnum && !x[0].flagactive)
{
buffer_put (buffer_1, x[0].left.s, x[0].left.len);
buffer_put (buffer_1, x[0].middle.s, x[0].middle.len);
buffer_put (buffer_1, x[0].right.s, x[0].right.len);
buffer_flush (buffer_1);
--xnum;
tmp = x[0];
for (i = 0; (unsigned)i < xnum; ++i)
x[i] = x[i + 1];
x[xnum] = tmp;
continue;
}
if ((xnum < xmax) && (numactive < maxactive))
{
i = byte_chr (inbuf, inbuflen, '\n');
if (inbuflen && ((unsigned)i == inbuflen))
{
if (!stralloc_catb (&partial, inbuf, inbuflen))
err (-1, "could not allocate enough memory");
inbuflen = 0;
continue;
}
if (((unsigned)i < inbuflen) || (!flag0 && partial.len))
{
if ((unsigned)i < inbuflen)
++i;
if (!stralloc_catb (&partial, inbuf, i))
err (-1, "could not allocate enough memory");
inbuflen -= i;
for (j = 0; (unsigned)j < inbuflen; ++j)
inbuf[j] = inbuf[j + i];
if (partial.len)
{
i = byte_chr (partial.s, partial.len, '\n');
i = byte_chr (partial.s, i, '\t');
i = byte_chr (partial.s, i, ' ');
if (!stralloc_copyb (&x[xnum].left, partial.s, i))
err (-1, "could not allocate enough memory");
if (!stralloc_copys (&x[xnum].middle, ""))
err (-1, "could not allocate enough memory");
if (!stralloc_copyb (&x[xnum].right, partial.s + i,
partial.len - i))
err (-1, "could not allocate enough memory");
x[xnum].flagactive = 0;
partial.len = i;
if (!stralloc_0 (&partial))
err (-1, "could not allocate enough memory");
if (ip4_scan (partial.s, ip))
{
dns_name4_domain (name, ip);
if (dns_resolvconfip (servers) == -1)
err (-1, "could not read `/etc/resolv.conf'");
if (dns_transmit_start (&x[xnum].dt, servers,
1, name, DNS_T_PTR, "\0\0\0\0") == -1)
errout (xnum);
else
{
x[xnum].flagactive = 1;
++numactive;
}
}
++xnum;
}
partial.len = 0;
continue;
}
}
break;
}
}
return 0;
}
| 9,679 |
C
|
.c
| 293 | 21.569966 | 78 | 0.449084 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,760 |
socket_send.c
|
dterweij_ndjbdns/socket_send.c
|
/*
* socket_send.c: This file is part of the `djbdns' project, originally written
* by Dr. D J Bernstein and later released under public-domain since late
* December 2007 (http://cr.yp.to/distributors.html).
*
* Copyright (C) 2009 - 2013 Prasad J Pandit
*
* This program is a free software; you can redistribute it and/or modify
* it under the terms of GNU General Public License as published by Free
* Software Foundation; either version 2 of the license or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* of FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <string.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "byte.h"
#include "socket.h"
int
socket_send4 (int s, char *buf, int len,
const char ip[4], uint16 port, void *src)
{
char cbuf[256];
struct iovec iov;
struct msghdr msgh;
struct sockaddr_in sa;
struct cmsghdr *cmsg = NULL;
byte_zero (&sa, sizeof (sa));
sa.sin_family = AF_INET;
uint16_pack_big ((char *)&sa.sin_port, port);
byte_copy ((char *)&sa.sin_addr, 4, ip);
memset (cbuf, 0, sizeof (cbuf));
memset (&msgh, 0, sizeof (msgh));
iov.iov_len = len;
iov.iov_base = buf;
msgh.msg_iov = &iov;
msgh.msg_iovlen = 1;
msgh.msg_name = &sa;
msgh.msg_namelen = sizeof (sa);
#ifdef IP_PKTINFO
struct in_pktinfo *p = NULL;
msgh.msg_control = cbuf;
msgh.msg_controllen = CMSG_SPACE (sizeof (*p));
cmsg = CMSG_FIRSTHDR (&msgh);
cmsg->cmsg_type = IP_PKTINFO;
cmsg->cmsg_level = IPPROTO_IP;
cmsg->cmsg_len = CMSG_LEN (sizeof (*p));
p = (struct in_pktinfo *) CMSG_DATA (cmsg);
#ifndef __CYGWIN__
p->ipi_spec_dst = *(struct in_addr *)src;
#endif
#elif defined IP_SENDSRCADDR
struct in_addr *p = NULL;
msgh.msg_control = cbuf;
msgh.msg_controllen = CMSG_SPACE (sizeof (*p));
cmsg = CMSG_FIRSTHDR (&msgh);
cmsg->cmsg_type = IP_SENDSRCADDR;
cmsg->cmsg_level = IPPROTO_IP;
cmsg->cmsg_len = CMSG_LEN (sizeof (*p));
p = (struct in_addr *)CMSG_DATA (cmsg);
p->s_addr = *(struct in_addr *)src;
#endif
msgh.msg_flags = 0;
msgh.msg_controllen = cmsg ? cmsg->cmsg_len : 0;
return sendmsg (s, &msgh, 0);
}
| 2,657 |
C
|
.c
| 76 | 31.263158 | 79 | 0.674337 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,762 |
dnsmx.c
|
dterweij_ndjbdns/dnsmx.c
|
/*
* dnsmx.c: This file is part of the `djbdns' project, originally written
* by Dr. D J Bernstein and later released under public-domain since late
* December 2007 (http://cr.yp.to/distributors.html).
*
* Copyright (C) 2009 - 2012 Prasad J Pandit
*
* This program is a free software; you can redistribute it and/or modify
* it under the terms of GNU General Public License as published by Free
* Software Foundation; either version 2 of the license or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* of FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <err.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <getopt.h>
#include "version.h"
#include "str.h"
#include "fmt.h"
#include "dns.h"
#include "byte.h"
#include "buffer.h"
#include "strerr.h"
#include "uint16.h"
static char *q;
static stralloc out;
static stralloc fqdn;
char strnum[FMT_ULONG];
static char seed[128];
static char *prog = NULL;
void
usage (void)
{
printf ("Usage: %s <domain-name> [<domain-name> ...]\n", prog);
}
void
printh (void)
{
usage ();
printf ("\n Options:\n");
printf ("%-17s %s\n", " -h --help", "print this help");
printf ("%-17s %s\n", " -v --version", "print version information");
printf ("\nReport bugs to <[email protected]>\n");
}
int
check_option (int argc, char *argv[])
{
int n = 0, ind = 0;
const char optstr[] = "+:hv";
struct option lopt[] = \
{
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'v' },
{ 0, 0, 0, 0 }
};
if (argc < 2)
{
usage ();
exit (0);
}
opterr = optind = 0;
while ((n = getopt_long (argc, argv, optstr, lopt, &ind)) != -1)
{
switch (n)
{
case 'h':
printh ();
exit (0);
case 'v':
printf ("%s is part of djbdns version %s\n", prog, VERSION);
exit (0);
default:
errx (-1, "unknown option `%c', see: --help", optopt);
}
}
return optind;
}
int
main (int argc, char *argv[])
{
char *x = NULL;
uint16 pref = 0;
int i = 0, j = 0;
prog = strdup ((x = strrchr (argv[0], '/')) != NULL ? x + 1 : argv[0]);
i = check_option (argc, argv);
argv += i;
argc -= i;
dns_random_init (seed);
while (*argv)
{
if (!stralloc_copys (&fqdn, *argv))
err (-1, "could not allocate enough memory");
if (dns_mx (&out, &fqdn) == -1)
errx (-1, "could not find MX records for `%s'", *argv);
if (!out.len)
{
if (!dns_domain_fromdot (&q, *argv, str_len (*argv)))
err (-1, "could not allocate enough memory");
if (!stralloc_copys (&out, "0 "))
err (-1, "could not allocate enough memory");
if (!dns_domain_todot_cat (&out, q))
err (-1, "could not allocate enough memory");
if (!stralloc_cats (&out, "\n"))
err (-1, "could not allocate enough memory");
buffer_put (buffer_1, out.s, out.len);
}
else
{
i = 0;
while ((unsigned)i + 2 < out.len)
{
j = byte_chr (out.s + i + 2, out.len - i - 2, 0);
uint16_unpack_big (out.s + i, &pref);
buffer_put (buffer_1, strnum, fmt_ulong (strnum, pref));
buffer_puts (buffer_1, " ");
buffer_put (buffer_1, out.s + i + 2, j);
buffer_puts (buffer_1, "\n");
i += j + 3;
}
}
++argv;
}
buffer_flush (buffer_1);
return 0;
}
| 4,106 |
C
|
.c
| 135 | 24.059259 | 78 | 0.553979 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,765 |
readclose.h
|
dterweij_ndjbdns/readclose.h
|
#pragma once
#include "stralloc.h"
extern int readclose_append(int,stralloc *,unsigned int);
extern int readclose(int,stralloc *,unsigned int);
| 146 |
C
|
.c
| 4 | 35 | 57 | 0.8 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,766 |
roots.c
|
dterweij_ndjbdns/roots.c
|
/*
* roots.c: This file is part of the `djbdns' project, originally
* written by Dr. D J Bernstein and later released under public-domain since
* late December 2007 (http://cr.yp.to/distributors.html).
*
* Copyright (C) 2009 - 2013 Prasad J Pandit
*
* This program is a free software; you can redistribute it and/or modify
* it under the terms of GNU General Public License as published by Free
* Software Foundation; either version 2 of the license or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* of FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <err.h>
#include <fcntl.h>
#include <dirent.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include "ip4.h"
#include "dns.h"
#include "str.h"
#include "byte.h"
#include "open.h"
#include "error.h"
#include "roots.h"
#include "openreadclose.h"
static stralloc data;
static int
roots_find (char *q)
{
int i = 0, j = 0;
while ((unsigned)i < data.len)
{
j = dns_domain_length (data.s + i);
if (dns_domain_equal (data.s + i, q))
return i + j;
i += j;
i += 64;
}
return -1;
}
static int
roots_search (char *q)
{
int r = 0;
for (;;)
{
if ((r = roots_find (q)) >= 0)
return r;
if (!*q)
return -1; /* user misconfiguration */
q = q + *q;
q++;
}
}
static unsigned char
roots_extract_name (char *dn, const char *s)
{
unsigned char l = 0, n = 0;
while (*s)
{
n = *s++;
while (n--)
dn[l++] = *s++;
dn[l++] = *s == 0 ? *s : '.';
}
return l;
}
int
roots (char servers[64], char *q)
{
int r = 0;
if ((r = roots_find (q)) == -1)
return 0;
byte_copy (servers, 64, data.s + r);
return 1;
}
int
roots_same (char *q, char *q2)
{
return roots_search (q) == roots_search (q2);
}
void
roots_display (void)
{
char dn[255];
unsigned short i = 0;
while (i < data.len)
{
unsigned char j = 0, n = 0;
memset (dn, 0, sizeof (dn));
n = roots_extract_name (dn, data.s + i);
warnx ("%s:", dn[0] == '\0' ? "roots" : dn);
i += n + 1;
while (j < 64)
{
if (data.s[i] != 0)
warnx(" %hhu.%hhu.%hhu.%hhu",
data.s[i], data.s[i+1], data.s[i+2], data.s[i+3]);
i += 4;
j += 4;
}
}
}
static int
init2 (DIR *dir)
{
char roots = 0;
char servers[64];
static stralloc text;
static char *q = NULL;
const char *fqdn = NULL;
struct dirent *d = NULL;
int i = 0, j = 0, serverslen = 0;
errno = 0;
while ((d = readdir (dir)))
{
if (d->d_name[0] == '.')
continue;
memset (&text, 0, sizeof (text));
if (openreadclose (d->d_name, &text, 32) != 1)
return 0;
fqdn = d->d_name;
if (str_equal (fqdn, "roots"))
{
roots = 1;
fqdn = ".";
}
if (!dns_domain_fromdot (&q, fqdn, str_len (fqdn)))
return 0;
memset (servers, 0, sizeof (servers));
for (i = 0, j = 0, serverslen = 0; (unsigned)i < text.len; ++i)
{
if (text.s[i] == '\n')
{
if (serverslen <= 60)
if (ip4_scan (text.s + j, servers + serverslen))
serverslen += 4;
j = i + 1;
}
}
if (!stralloc_catb (&data, q, dns_domain_length (q)))
return 0;
if (!stralloc_catb (&data, servers, 64))
return 0;
errno = 0;
}
if (!roots)
err (-1, "could not access file: servers/roots");
return !errno;
}
static int
init1 (void)
{
int r = 0;
DIR *dir = NULL;
if (chdir ("servers") == -1)
return 0;
if (!(dir = opendir (".")))
return 0;
r = init2 (dir);
closedir (dir);
return r;
}
int
roots_init (void)
{
int r = 0, fddir = 0;
if (!stralloc_copys (&data, ""))
return 0;
if ((fddir = open (".", O_RDONLY | O_NDELAY)) == -1)
return 0;
r = init1 ();
if (fchdir (fddir) == -1)
r = 0;
close(fddir);
return r;
}
| 4,676 |
C
|
.c
| 188 | 19.053191 | 78 | 0.530759 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,775 |
dnsipq.c
|
dterweij_ndjbdns/dnsipq.c
|
/*
* dnsipq.c: This file is part of the `djbdns' project, originally written
* by Dr. D J Bernstein and later released under public-domain since late
* December 2007 (http://cr.yp.to/distributors.html).
*
* Copyright (C) 2009 - 2012 Prasad J Pandit
*
* This program is a free software; you can redistribute it and/or modify
* it under the terms of GNU General Public License as published by Free
* Software Foundation; either version 2 of the license or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* of FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include "version.h"
#include "ip4.h"
#include "dns.h"
#include "buffer.h"
#include "strerr.h"
char str[IP4_FMT];
static char seed[128];
static stralloc in;
static stralloc out;
static stralloc fqdn;
static char *prog = NULL;
void
usage (void)
{
printf ("Usage: %s <domain-name> [<domain-name> ...]\n", prog);
}
void
printh (void)
{
usage ();
printf ("\n Options:\n");
printf ("%-17s %s\n", " -h --help", "print this help");
printf ("%-17s %s\n", " -v --version", "print version information");
printf ("\nReport bugs to <[email protected]>\n");
}
int
check_option (int argc, char *argv[])
{
int n = 0, ind = 0;
const char optstr[] = "+:hv";
struct option lopt[] = \
{
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'v' },
{ 0, 0, 0, 0 }
};
if (argc < 2)
{
usage ();
exit (0);
}
opterr = optind = 0;
while ((n = getopt_long (argc, argv, optstr, lopt, &ind)) != -1)
{
switch (n)
{
case 'h':
printh ();
exit (0);
case 'v':
printf ("%s is part of djbdns version %s\n", prog, VERSION);
exit (0);
default:
errx (-1, "unknown option `%c', see: --help", optopt);
}
}
return optind;
}
int
main (int argc,char *argv[])
{
int i = 0;
char *x = NULL;
prog = strdup ((x = strrchr (argv[0], '/')) != NULL ? x + 1 : argv[0]);
i = check_option (argc, argv);
argv += i;
argc -= i;
dns_random_init (seed);
while (*argv)
{
if (!stralloc_copys (&in, *argv))
err (-1, "could not allocate enough memory");
if (dns_ip4_qualify (&out, &fqdn, &in) == -1)
err (-1, "could not find IP address for `%s'", *argv);
buffer_put (buffer_1, fqdn.s, fqdn.len);
buffer_puts (buffer_1, " ");
for (i = 0; (unsigned)i + 4 <= out.len; i += 4)
{
buffer_put (buffer_1, str, ip4_fmt (str, out.s + i));
buffer_puts (buffer_1, " ");
}
buffer_puts (buffer_1, "\n");
++argv;
}
buffer_flush (buffer_1);
return 0;
}
| 3,272 |
C
|
.c
| 113 | 24.123894 | 78 | 0.589547 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,776 |
printpacket.h
|
dterweij_ndjbdns/printpacket.h
|
#pragma once
#include "stralloc.h"
extern unsigned int printpacket_cat(stralloc *,char *,unsigned int);
| 106 |
C
|
.c
| 3 | 33.666667 | 68 | 0.792079 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,779 |
openreadclose.h
|
dterweij_ndjbdns/openreadclose.h
|
#pragma once
#include "stralloc.h"
extern int openreadclose(const char *,stralloc *,unsigned int);
| 101 |
C
|
.c
| 3 | 32 | 63 | 0.791667 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,783 |
tinydns-data.c
|
dterweij_ndjbdns/tinydns-data.c
|
/*
* tinydns-data.c: This file is part of the `djbdns' project, originally
* written by Dr. D J Bernstein and later released under public-domain
* since late December 2007 (http://cr.yp.to/distributors.html).
*
* Copyright (C) 2009 - 2012 Prasad J Pandit
*
* This program is a free software; you can redistribute it and/or modify
* it under the terms of GNU General Public License as published by Free
* Software Foundation; either version 2 of the license or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* of FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <err.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <getopt.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "version.h"
#include "dns.h"
#include "str.h"
#include "fmt.h"
#include "ip4.h"
#include "byte.h"
#include "case.h"
#include "scan.h"
#include "open.h"
#include "getln.h"
#include "buffer.h"
#include "strerr.h"
#include "uint16.h"
#include "uint32.h"
#include "cdb_make.h"
#include "stralloc.h"
#define TTL_NS 259200
#define TTL_POSITIVE 86400
#define TTL_NEGATIVE 2560
static char *prog = NULL;
void
ttdparse (stralloc *sa, char ttd[8])
{
char ch = 0;
unsigned int i = 0;
byte_zero (ttd, 8);
for (i = 0; (i < 16) && (i < sa->len); i++)
{
ch = sa->s[i];
if ((ch >= '0') && (ch <= '9'))
ch -= '0';
else if ((ch >= 'a') && (ch <= 'f'))
ch -= 'a' - 10;
else
ch = 0;
if (!(i & 1))
ch <<= 4;
ttd[i >> 1] |= ch;
}
}
void
locparse (stralloc *sa, char loc[2])
{
loc[0] = (sa->len > 0) ? sa->s[0] : 0;
loc[1] = (sa->len > 1) ? sa->s[1] : 0;
}
void
ipprefix_cat (stralloc *out, char *s)
{
char ch = 0;
unsigned int j = 0;
unsigned long u = 0;
for (;;)
{
if (*s == '.')
s++;
else
{
j = scan_ulong (s, &u);
if (!j)
return;
s += j;
ch = u;
if (!stralloc_catb (out, &ch, 1))
err (-1, "could not allocate enough memory");
}
}
}
void
txtparse (stralloc *sa)
{
char ch = 0;
unsigned int i = 0;
unsigned int j = 0;
i = j = 0;
while (i < sa->len)
{
ch = sa->s[i++];
if (ch == '\\')
{
if (i >= sa->len)
break;
ch = sa->s[i++];
if ((ch >= '0') && (ch <= '7'))
{
ch -= '0';
if ((i < sa->len) && (sa->s[i] >= '0') && (sa->s[i] <= '7'))
{
ch <<= 3;
ch += sa->s[i++] - '0';
if ((i < sa->len) && (sa->s[i] >= '0')
&& (sa->s[i] <= '7'))
{
ch <<= 3;
ch += sa->s[i++] - '0';
}
}
}
}
sa->s[j++] = ch;
}
sa->len = j;
}
char defaultsoa[20];
void
defaultsoa_init (int fd)
{
struct stat st;
if (fstat (fd, &st) == -1)
err (-1, "unable to stat data");
uint32_pack_big (defaultsoa, st.st_mtime);
if (byte_equal (defaultsoa, 4, "\0\0\0\0"))
defaultsoa[3] = 1;
byte_copy (defaultsoa + 4, 16,
"\0\0\100\000\0\0\010\000\0\020\000\000\0\0\012\000");
}
int fdcdb;
struct cdb_make cdb;
static stralloc key;
static stralloc result;
void
rr_add (const char *buf, unsigned int len)
{
if (!stralloc_catb (&result, buf, len))
err (-1, "could not allocate enough memory");
}
void
rr_addname (const char *d)
{
rr_add (d, dns_domain_length (d));
}
void
rr_start (const char type[2], unsigned long ttl,
const char ttd[8], const char loc[2])
{
char buf[4];
if (!stralloc_copyb (&result, type, 2))
err (-1, "could not allocate enough memory");
if (byte_equal (loc, 2, "\0\0"))
rr_add ("=", 1);
else
{
rr_add (">", 1);
rr_add (loc, 2);
}
uint32_pack_big (buf, ttl);
rr_add (buf, 4);
rr_add (ttd, 8);
}
void
rr_finish (const char *owner)
{
if (byte_equal (owner, 2, "\1*"))
{
owner += 2;
result.s[2] -= 19;
}
if (!stralloc_copyb (&key, owner, dns_domain_length (owner)))
err (-1, "could not allocate enough memory");
case_lowerb (key.s, key.len);
if (cdb_make_add (&cdb, key.s, key.len, result.s, result.len) == -1)
errx (-1, "could not create file `data.tmp'");
}
buffer b;
char bspace[1024];
int match = 1;
static stralloc line;
unsigned long linenum = 0;
#define NUMFIELDS 15
static stralloc f[NUMFIELDS];
static char *d1;
static char *d2;
char dptr[DNS_NAME4_DOMAIN];
char strnum[FMT_ULONG];
void
syntaxerror (const char *why)
{
strnum[fmt_ulong (strnum, linenum)] = 0;
errx (-1, "could not parse data line: %s: %s", strnum, why);
}
void
usage (void)
{
printf ("Usage: %s [OPTIONS]\n", prog);
}
void
printh (void)
{
usage ();
printf ("\n Options:\n");
printf ("%-17s %s\n", " -h --help", "print this help");
printf ("%-17s %s\n", " -v --version", "print version information");
printf ("\nReport bugs to <[email protected]>\n");
}
int
check_option (int argc, char *argv[])
{
int n = 0, ind = 0;
const char optstr[] = "+:hv";
struct option lopt[] = \
{
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'v' },
{ 0, 0, 0, 0 }
};
opterr = optind = 0;
while ((n = getopt_long (argc, argv, optstr, lopt, &ind)) != -1)
{
switch (n)
{
case 'h':
printh ();
exit (0);
case 'v':
printf ("%s is part of djbdns version %s\n", prog, VERSION);
exit (0);
default:
errx (-1, "unknown option `%c', see: --help", optopt);
}
}
return optind;
}
int
main(int argc, char *argv[])
{
int fddata = 0;
unsigned int i = 0, j = 0, k = 0;
unsigned long u = 0;
unsigned long ttl = 0;
char ch = 0;
char *x = NULL;
char ttd[8], loc[2];
char ip[4], type[2];
char soa[20], buf[4];
prog = strdup ((x = strrchr (argv[0], '/')) != NULL ? x + 1 : argv[0]);
i = check_option (argc, argv);
argv += i;
argc -= i;
umask(022);
if ((fddata = open_read ("data")) == -1)
err (-1, "could not open file `data'");
defaultsoa_init (fddata);
buffer_init (&b, buffer_unixread, fddata, bspace, sizeof bspace);
if ((fdcdb = open_trunc ("data.tmp")) == -1)
err (-1, "could not create file `data.tmp'");
if (cdb_make_start (&cdb, fdcdb) == -1)
err (-1, "could not create file `data.tmp'");
while (match)
{
linenum++;
if (getln (&b, &line, &match, '\n') == -1)
err (-1, "could not read line: %ld", linenum);
while (line.len)
{
ch = line.s[line.len - 1];
if ((ch != ' ') && (ch != '\t') && (ch != '\n'))
break;
--line.len;
}
if (!line.len)
continue;
if (line.s[0] == '#')
continue;
if (line.s[0] == '-')
continue;
j = 1;
for (i = 0; i < NUMFIELDS; i++)
{
if (j >= line.len)
{
if (!stralloc_copys (&f[i], ""))
err (-1, "could not allocate enough memory");
}
else
{
k = byte_chr (line.s + j, line.len - j, ':');
if (!stralloc_copyb (&f[i], line.s + j, k))
err (-1, "could not allocate enough memory");
j += k + 1;
}
}
switch (line.s[0])
{
case '%':
locparse (&f[0], loc);
if (!stralloc_copyb (&key, "\0%", 2))
err (-1, "could not allocate enough memory");
if (!stralloc_0 (&f[1]))
err (-1, "could not allocate enough memory");
ipprefix_cat (&key, f[1].s);
if (cdb_make_add(&cdb,key.s,key.len,loc,2) == -1)
err (-1, "could not create file `data.tmp'");
break;
case 'Z':
if (!dns_domain_fromdot (&d1, f[0].s, f[0].len))
err (-1, "could not allocate enough memory");
if (!stralloc_0 (&f[3]))
err (-1, "could not allocate enough memory");
if (!scan_ulong (f[3].s, &u))
uint32_unpack_big (defaultsoa, (uint32 *)&u);
uint32_pack_big (soa, u);
if (!stralloc_0 (&f[4]))
err (-1, "could not allocate enough memory");
if (!scan_ulong (f[4].s, &u))
uint32_unpack_big (defaultsoa + 4, (uint32 *)&u);
uint32_pack_big (soa + 4, u);
if (!stralloc_0 (&f[5]))
err (-1, "could not allocate enough memory");
if (!scan_ulong (f[5].s, &u))
uint32_unpack_big (defaultsoa + 8, (uint32 *)&u);
uint32_pack_big (soa + 8, u);
if (!stralloc_0 (&f[6]))
err (-1, "could not allocate enough memory");
if (!scan_ulong (f[6].s, &u))
uint32_unpack_big (defaultsoa + 12, (uint32 *)&u);
uint32_pack_big (soa + 12, u);
if (!stralloc_0 (&f[7]))
err (-1, "could not allocate enough memory");
if (!scan_ulong (f[7].s, &u))
uint32_unpack_big (defaultsoa + 16, (uint32 *)&u);
uint32_pack_big (soa + 16, u);
if (!stralloc_0 (&f[8]))
err (-1, "could not allocate enough memory");
if (!scan_ulong(f[8].s,&ttl))
ttl = TTL_NEGATIVE;
ttdparse (&f[9], ttd);
locparse (&f[10], loc);
rr_start (DNS_T_SOA, ttl, ttd, loc);
if (!dns_domain_fromdot (&d2, f[1].s, f[1].len))
err (-1, "could not allocate enough memory");
rr_addname (d2);
if (!dns_domain_fromdot (&d2, f[2].s, f[2].len))
err (-1, "could not allocate enough memory");
rr_addname (d2);
rr_add (soa, 20);
rr_finish (d1);
break;
case '.':
case '&':
if (!dns_domain_fromdot (&d1, f[0].s, f[0].len))
err (-1, "could not allocate enough memory");
if (!stralloc_0 (&f[3]))
err (-1, "could not allocate enough memory");
if (!scan_ulong (f[3].s, &ttl))
ttl = TTL_NS;
ttdparse (&f[4], ttd);
locparse (&f[5], loc);
if (!stralloc_0 (&f[1]))
err (-1, "could not allocate enough memory");
if (byte_chr (f[2].s, f[2].len, '.') >= f[2].len)
{
if (!stralloc_cats (&f[2], ".ns."))
err (-1, "could not allocate enough memory");
if (!stralloc_catb (&f[2], f[0].s, f[0].len))
err (-1, "could not allocate enough memory");
}
if (!dns_domain_fromdot (&d2, f[2].s, f[2].len))
err (-1, "could not allocate enough memory");
if (line.s[0] == '.')
{
rr_start (DNS_T_SOA, ttl ? TTL_NEGATIVE : 0, ttd, loc);
rr_addname (d2);
rr_add ("\12hostmaster", 11);
rr_addname (d1);
rr_add (defaultsoa, 20);
rr_finish (d1);
}
rr_start (DNS_T_NS, ttl, ttd, loc);
rr_addname (d2);
rr_finish (d1);
if (ip4_scan (f[1].s, ip))
{
rr_start (DNS_T_A, ttl, ttd, loc);
rr_add (ip, 4);
rr_finish (d2);
}
break;
case '+':
case '=':
if (!dns_domain_fromdot (&d1, f[0].s, f[0].len))
err (-1, "could not allocate enough memory");
if (!stralloc_0 (&f[2]))
err (-1, "could not allocate enough memory");
if (!scan_ulong (f[2].s, &ttl))
ttl = TTL_POSITIVE;
ttdparse (&f[3], ttd);
locparse (&f[4], loc);
if (!stralloc_0 (&f[1]))
err (-1, "could not allocate enough memory");
if (ip4_scan (f[1].s, ip))
{
rr_start (DNS_T_A, ttl, ttd, loc);
rr_add (ip, 4);
rr_finish (d1);
if (line.s[0] == '=')
{
dns_name4_domain (dptr,ip);
rr_start (DNS_T_PTR, ttl, ttd, loc);
rr_addname (d1);
rr_finish (dptr);
}
}
break;
case '@':
if (!dns_domain_fromdot (&d1, f[0].s, f[0].len))
err (-1, "could not allocate enough memory");
if (!stralloc_0 (&f[4]))
err (-1, "could not allocate enough memory");
if (!scan_ulong (f[4].s, &ttl))
ttl = TTL_POSITIVE;
ttdparse (&f[5], ttd);
locparse (&f[6], loc);
if (!stralloc_0 (&f[1]))
err (-1, "could not allocate enough memory");
if (byte_chr (f[2].s, f[2].len, '.') >= f[2].len)
{
if (!stralloc_cats (&f[2], ".mx."))
err (-1, "could not allocate enough memory");
if (!stralloc_catb (&f[2], f[0].s, f[0].len))
err (-1, "could not allocate enough memory");
}
if (!dns_domain_fromdot (&d2, f[2].s, f[2].len))
err (-1, "could not allocate enough memory");
if (!stralloc_0 (&f[3]))
err (-1, "could not allocate enough memory");
if (!scan_ulong (f[3].s, &u))
u = 0;
rr_start (DNS_T_MX, ttl, ttd, loc);
uint16_pack_big (buf, u);
rr_add (buf, 2);
rr_addname (d2);
rr_finish (d1);
if (ip4_scan (f[1].s, ip))
{
rr_start (DNS_T_A, ttl, ttd, loc);
rr_add (ip, 4);
rr_finish (d2);
}
break;
case '^':
case 'C':
if (!dns_domain_fromdot (&d1, f[0].s, f[0].len))
err (-1, "could not allocate enough memory");
if (!dns_domain_fromdot (&d2, f[1].s, f[1].len))
err (-1, "could not allocate enough memory");
if (!stralloc_0 (&f[2]))
err (-1, "could not allocate enough memory");
if (!scan_ulong (f[2].s, &ttl))
ttl = TTL_POSITIVE;
ttdparse (&f[3], ttd);
locparse (&f[4], loc);
if (line.s[0] == 'C')
rr_start (DNS_T_CNAME, ttl, ttd, loc);
else
rr_start (DNS_T_PTR, ttl, ttd, loc);
rr_addname (d2);
rr_finish (d1);
break;
case '\'':
if (!dns_domain_fromdot (&d1, f[0].s, f[0].len))
err (-1, "could not allocate enough memory");
if (!stralloc_0 (&f[2]))
err (-1, "could not allocate enough memory");
if (!scan_ulong (f[2].s, &ttl))
ttl = TTL_POSITIVE;
ttdparse (&f[3], ttd);
locparse (&f[4], loc);
rr_start (DNS_T_TXT, ttl, ttd, loc);
txtparse (&f[1]);
i = 0;
while (i < f[1].len)
{
k = f[1].len - i;
if (k > 127)
k = 127;
ch = k;
rr_add (&ch, 1);
rr_add (f[1].s + i, k);
i += k;
}
rr_finish (d1);
break;
case ':':
if (!dns_domain_fromdot (&d1, f[0].s, f[0].len))
err (-1, "could not allocate enough memory");
if (!stralloc_0 (&f[3]))
err (-1, "could not allocate enough memory");
if (!scan_ulong (f[3].s, &ttl))
ttl = TTL_POSITIVE;
ttdparse (&f[4], ttd);
locparse (&f[5], loc);
if (!stralloc_0 (&f[1]))
err (-1, "could not allocate enough memory");
scan_ulong (f[1].s, &u);
uint16_pack_big (type, u);
if (byte_equal (type, 2, DNS_T_AXFR))
syntaxerror (": type AXFR prohibited");
if (byte_equal (type, 2, "\0\0"))
syntaxerror (": type 0 prohibited");
if (byte_equal (type, 2, DNS_T_SOA))
syntaxerror (": type SOA prohibited");
if (byte_equal (type, 2, DNS_T_NS))
syntaxerror (": type NS prohibited");
if (byte_equal (type, 2, DNS_T_CNAME))
syntaxerror (": type CNAME prohibited");
if (byte_equal (type, 2, DNS_T_PTR))
syntaxerror (": type PTR prohibited");
if (byte_equal (type, 2, DNS_T_MX))
syntaxerror (": type MX prohibited");
txtparse (&f[2]);
rr_start (type, ttl, ttd, loc);
rr_add (f[2].s, f[2].len);
rr_finish (d1);
break;
default:
syntaxerror (": unrecognized leading character");
}
}
if (cdb_make_finish (&cdb) == -1)
err (-1, "could not create file `data.tmp'");
if (fsync (fdcdb) == -1)
err (-1, "could not create file `data.tmp'");
if (close (fdcdb) == -1)
err (-1, "could not create file `data.tmp'"); /* NFS stupidity */
if (rename ("data.tmp", "data.cdb") == -1)
err (-1, "could not move `data.tmp' to `data.cdb'");
return 0;
}
| 18,387 |
C
|
.c
| 557 | 23.131059 | 78 | 0.458988 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,784 |
tinydns-edit.c
|
dterweij_ndjbdns/tinydns-edit.c
|
/*
* tinydns-edit.c: This file is part of the `djbdns' project, originally
* written by Dr. D J Bernstein and later released under public-domain
* since late December 2007 (http://cr.yp.to/distributors.html).
*
* Copyright (C) 2009 - 2012 Prasad J Pandit
*
* This program is a free software; you can redistribute it and/or modify
* it under the terms of GNU General Public License as published by Free
* Software Foundation; either version 2 of the license or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* of FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <err.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <getopt.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "version.h"
#include "str.h"
#include "fmt.h"
#include "ip4.h"
#include "dns.h"
#include "scan.h"
#include "byte.h"
#include "open.h"
#include "getln.h"
#include "strerr.h"
#include "buffer.h"
#include "stralloc.h"
#define TTL_NS 259200
#define TTL_POSITIVE 86400
char *fn = NULL;
char *fnnew = NULL;
static char *prog = NULL;
char mode;
char targetip[4];
static char *target = NULL;
buffer b;
int fd = 0;
char bspace[1024];
buffer bnew;
int fdnew = 0;
char bnewspace[1024];
int match = 1;
static stralloc line;
#define NUMFIELDS 10
static stralloc f[NUMFIELDS];
static char *d1 = NULL;
static char *d2 = NULL;
char ip[4];
char ipstr[IP4_FMT];
char strnum[FMT_ULONG];
static int used[26];
static char *names[26];
void
put (const char *buf, unsigned int len)
{
if (buffer_putalign (&bnew, buf, len) == -1)
err (-1, "could not write `%s'", fnnew);
}
void
usage (void)
{
printf ("Usage: %s data data.new add ", prog);
printf ("[ns|childns|host|alias|mx] <domain> <a.b.c.d>\n");
}
void
printh (void)
{
usage ();
printf ("\n Options:\n");
printf ("%-17s %s\n", " -h --help", "print this help");
printf ("%-17s %s\n", " -v --version", "print version information");
printf ("\nReport bugs to <[email protected]>\n");
}
int
check_option (int argc, char *argv[])
{
int n = 0, ind = 0;
const char optstr[] = "+:hv";
struct option lopt[] = \
{
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'v' },
{ 0, 0, 0, 0 }
};
opterr = optind = 0;
while ((n = getopt_long (argc, argv, optstr, lopt, &ind)) != -1)
{
switch (n)
{
case 'h':
printh ();
exit (0);
case 'v':
printf ("%s is part of djbdns version %s\n", prog, VERSION);
exit (0);
default:
errx (-1, "unknown option `%c', see: --help", optopt);
}
}
return optind;
}
int
main (int argc, char *argv[])
{
char ch = 0;
struct stat st;
unsigned long ttl = 0;
unsigned i = 0, j = 0, k = 0;
prog = strdup ((d1 = strrchr (argv[0], '/')) != NULL ? d1 + 1 : argv[0]);
i = check_option (argc, argv);
argv += i;
argc -= i;
d1 = NULL;
if (argc < 6)
{
usage ();
return -1;
}
fn = *argv;
argv++;
fnnew = *argv;
argv++;
if (str_diff (*argv, "add"))
{
usage ();
return -1;
}
argv++;
if (str_equal (*argv, "ns"))
mode = '.';
else if (str_equal (*argv, "childns"))
mode = '&';
else if (str_equal (*argv, "host"))
mode = '=';
else if (str_equal (*argv, "alias"))
mode = '+';
else if (str_equal (*argv, "mx"))
mode = '@';
else
errx (-1, "invalid record type `%s'", *argv);
argv++;
if (!dns_domain_fromdot (&target, *argv, str_len (*argv)))
err (-1, "could not allocate enough memory");
argv++;
if (!ip4_scan (*argv, targetip))
errx (-1, "could not parse IP `%s'", *argv);
umask(077);
fd = open_read (fn);
if (fd == -1)
err (-1, "could not read from `%s'", fn);
if (fstat (fd, &st) == -1)
err (-1, "could not read from `%s'", fn);
buffer_init (&b, buffer_unixread, fd, bspace, sizeof bspace);
fdnew = open_trunc (fnnew);
if (fdnew == -1)
err (-1, "could not write to `%s'", fnnew);
if (fchmod (fdnew, st.st_mode & 0644) == -1)
err (-1, "could not write to `%s'", fnnew);
buffer_init (&bnew, buffer_unixwrite, fdnew, bnewspace, sizeof bnewspace);
switch (mode)
{
case '.':
case '&':
ttl = TTL_NS;
for (i = 0; i < 26; i++)
{
ch = 'a' + i;
if (!stralloc_copyb (&f[0], &ch, 1))
err (-1, "could not allocate enough memory");
if (!stralloc_cats (&f[0], ".ns."))
err (-1, "could not allocate enough memory");
if (!dns_domain_todot_cat (&f[0], target))
err (-1, "could not allocate enough memory");
if (!dns_domain_fromdot (&names[i], f[0].s, f[0].len))
err (-1, "could not allocate enough memory");
}
break;
case '+':
case '=':
ttl = TTL_POSITIVE;
break;
case '@':
ttl = TTL_POSITIVE;
for (i = 0; i < 26; i++)
{
ch = 'a' + i;
if (!stralloc_copyb (&f[0], &ch, 1))
err (-1, "could not allocate enough memory");
if (!stralloc_cats (&f[0], ".mx."))
err (-1, "could not allocate enough memory");
if (!dns_domain_todot_cat (&f[0], target))
err (-1, "could not allocate enough memory");
if (!dns_domain_fromdot (&names[i], f[0].s, f[0].len))
err (-1, "could not allocate enough memory");
}
break;
}
while (match)
{
if (getln (&b, &line, &match, '\n') == -1)
err (-1, "could not read from `%s'", fn);
put (line.s, line.len);
if (line.len && !match)
put ("\n", 1);
while (line.len)
{
ch = line.s[line.len - 1];
if ((ch != ' ') && (ch != '\t') && (ch != '\n'))
break;
--line.len;
}
if (!line.len || line.s[0] == '#')
continue;
j = 1;
for (i = 0; i < NUMFIELDS; i++)
{
if (j >= line.len)
{
if (!stralloc_copys (&f[i], ""))
err (-1, "could not allocate enough memory");
}
else
{
k = byte_chr (line.s + j, line.len - j, ':');
if (!stralloc_copyb (&f[i], line.s + j, k))
err (-1, "could not allocate enough memory");
j += k + 1;
}
}
switch(mode)
{
case '.':
case '&':
if (line.s[0] == mode)
{
if (!dns_domain_fromdot (&d1, f[0].s, f[0].len))
err (-1, "could not allocate enough memory");
if (dns_domain_equal (d1, target))
{
if (byte_chr (f[2].s, f[2].len, '.') >= f[2].len)
{
if (!stralloc_cats (&f[2], ".ns."))
err (-1, "could not allocate enough memory");
if (!stralloc_catb (&f[2], f[0].s, f[0].len))
err (-1, "could not allocate enough memory");
}
if (!dns_domain_fromdot (&d2, f[2].s, f[2].len))
err (-1, "could not allocate enough memory");
if (!stralloc_0 (&f[3]))
err (-1, "could not allocate enough memory");
if (!scan_ulong (f[3].s, &ttl))
ttl = TTL_NS;
for (i = 0; i < 26; i++)
{
if (dns_domain_equal (d2, names[i]))
{
used[i] = 1;
break;
}
}
}
}
break;
case '=':
if (line.s[0] == '=')
{
if (!dns_domain_fromdot (&d1, f[0].s, f[0].len))
err (-1, "could not allocate enough memory");
if (dns_domain_equal (d1, target))
errx (-1, "host name is already used");
if (!stralloc_0 (&f[1]))
err (-1, "could not allocate enough memory");
if (ip4_scan (f[1].s, ip))
if (byte_equal(ip, 4, targetip))
errx (-1, "IP address is already used");
}
break;
case '@':
if (line.s[0] == '@')
{
if (!dns_domain_fromdot (&d1, f[0].s, f[0].len))
err (-1, "could not allocate enough memory");
if (dns_domain_equal (d1, target))
{
if (byte_chr (f[2].s, f[2].len, '.') >= f[2].len)
{
if (!stralloc_cats (&f[2], ".mx."))
err (-1, "could not allocate enough memory");
if (!stralloc_catb (&f[2], f[0].s, f[0].len))
err (-1, "could not allocate enough memory");
}
if (!dns_domain_fromdot (&d2, f[2].s, f[2].len))
err (-1, "could not allocate enough memory");
if (!stralloc_0 (&f[4]))
err (-1, "could not allocate enough memory");
if (!scan_ulong (f[4].s, &ttl))
ttl = TTL_POSITIVE;
for (i = 0; i < 26; i++)
{
if (dns_domain_equal (d2, names[i]))
{
used[i] = 1;
break;
}
}
}
}
break;
}
}
if (!stralloc_copyb (&f[0], &mode, 1))
err (-1, "could not allocate enough memory");
if (!dns_domain_todot_cat (&f[0], target))
err (-1, "could not allocate enough memory");
if (!stralloc_cats (&f[0], ":"))
err (-1, "could not allocate enough memory");
if (!stralloc_catb (&f[0], ipstr, ip4_fmt (ipstr, targetip)))
err (-1, "could not allocate enough memory");
switch (mode)
{
case '.':
case '&':
case '@':
for (i = 0; i < 26; i++)
{
if (!used[i])
break;
}
if (i >= 26)
errx (-1, "too many records for domain `%s'", target);
ch = 'a' + i;
if (!stralloc_cats (&f[0], ":"))
err (-1, "could not allocate enough memory");
if (!stralloc_catb (&f[0], &ch, 1))
err (-1, "could not allocate enough memory");
if (mode == '@')
if (!stralloc_cats (&f[0], ":"))
err (-1, "could not allocate enough memory");
break;
}
if (!stralloc_cats (&f[0], ":"))
err (-1, "could not allocate enough memory");
if (!stralloc_catb (&f[0], strnum, fmt_ulong (strnum, ttl)))
err (-1, "could not allocate enough memory");
if (!stralloc_cats (&f[0], "\n"))
err (-1, "could not allocate enough memory");
put (f[0].s, f[0].len);
if (buffer_flush (&bnew) == -1)
err (-1, "could not write to `%s'", fnnew);
if (fsync (fdnew) == -1)
err (-1, "could not write to `%s'", fnnew);
if (close (fdnew) == -1)
err (-1, "could not write to `%s'", fnnew); /* NFS dorks */
if (rename (fnnew, fn) == -1)
err (-1, "could not move `%s' to `%s'", fnnew, fn);
return 0;
}
| 12,177 |
C
|
.c
| 371 | 23.347709 | 78 | 0.46817 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,798 |
alloc.h
|
dterweij_ndjbdns/alloc.h
|
#pragma once
extern /*@null@*//*@out@*/char *alloc ();
extern int alloc_re ();
extern void alloc_free ();
| 109 |
C
|
.c
| 4 | 25.5 | 41 | 0.656863 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,800 |
tcprules.c
|
dterweij_ndjbdns/tcprules.c
|
/*
* tcprules.c: This file is part of the `djbdns' project, originally written
* by Dr. D J Bernstein and later released under public-domain since late
* December 2007 (http://cr.yp.to/distributors.html).
*
* Copyright (C) 2009 - 2012 Prasad J Pandit
*
* This program is a free software; you can redistribute it and/or modify
* it under the terms of GNU General Public License as published by Free
* Software Foundation; either version 2 of the license or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* of FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include "fmt.h"
#include "str.h"
#include "byte.h"
#include "open.h"
#include "scan.h"
#include "getln.h"
#include "buffer.h"
#include "strerr.h"
#include "stralloc.h"
#include "cdb_make.h"
#include "version.h"
char *fn = NULL;
char *fntemp = NULL;
unsigned long linenum = 0;
static char *prog = NULL;
int match = 1;
stralloc key;
stralloc data;
stralloc line;
stralloc address;
struct cdb_make c;
void
usage (void)
{
printf ("Usage: %s <rules.cdb> <rules.tmp>\n", prog);
}
void
printh (void)
{
usage ();
printf ("\n Options:\n");
printf ("%-17s %s\n", " -h --help", "print this help");
printf ("%-17s %s\n", " -v --version", "print version information");
printf ("\nReport bugs to <[email protected]>\n");
}
int
check_option (int argc, char *argv[])
{
int n = 0, ind = 0;
const char optstr[] = "+:hv";
struct option lopt[] = \
{
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'v' },
{ 0, 0, 0, 0 }
};
opterr = optind = 0;
while ((n = getopt_long (argc, argv, optstr, lopt, &ind)) != -1)
{
switch (n)
{
case 'h':
printh ();
exit (0);
case 'v':
printf ("%s is part of djbdns version %s\n", prog, VERSION);
exit (0);
default:
errx (-1, "unknown option `%c', see: --help", optopt);
}
}
return optind;
}
void
die_bad (void)
{
if (!stralloc_0 (&line))
err (-1, "could not allocate enough memory");
err (-1, "unable to parse this line: %s", line.s);
}
void
die_write (void)
{
err (-1, "unable to write to %s", fntemp);
}
stralloc sanum;
char strnum[FMT_ULONG];
void
getnum (char *buf, int len, unsigned long *u)
{
if (!stralloc_copyb (&sanum, buf, len))
err (-1, "could not allocate enough memory");
if (!stralloc_0 (&sanum))
err (-1, "could not allocate enough memory");
if (sanum.s[scan_ulong (sanum.s, u)])
die_bad ();
}
void
doaddressdata (void)
{
int i = 0;
int left = 0, right = 0;
unsigned long bot = 0, top = 0;
if (byte_chr (address.s, address.len, '=') == address.len)
{
if (byte_chr (address.s, address.len, '@') == address.len)
{
i = byte_chr (address.s, address.len, '-');
if ((unsigned)i < address.len)
{
left = byte_rchr (address.s, i, '.');
left = (left == i) ? 0 : left + 1;
++i;
right = i + byte_chr (address.s + i, address.len - i, '.');
getnum (address.s + left, i - 1 - left, &bot);
getnum (address.s + i, right - i, &top);
if (top > 255)
top = 255;
while (bot <= top)
{
if (!stralloc_copyb (&key, address.s, left))
err (-1, "could not allocate enough memory");
if (!stralloc_catb (&key, strnum, fmt_ulong (strnum, bot)))
err (-1, "could not allocate enough memory");
if (!stralloc_catb (&key, address.s + right,
address.len - right))
err (-1, "could not allocate enough memory");
if (cdb_make_add (&c, key.s, key.len,
data.s, data.len) == -1)
die_write ();
++bot;
}
return;
}
}
}
if (cdb_make_add (&c, address.s, address.len, data.s, data.len) == -1)
die_write ();
}
int
main (int argc, char *argv[])
{
buffer b;
char bspace[1024];
int fd = 0, len = 0;
int i = 0, colon = 0;
char *x = NULL, ch = 0;
prog = strdup ((x = strrchr (argv[0], '/')) != NULL ? x + 1 : argv[0]);
i = check_option (argc, argv);
argv += i;
argc -= i;
if (argc < 2)
{
usage ();
exit (0);
}
fn = argv[0];
if (!fn)
usage ();
fntemp = argv[1];
if (!fntemp)
usage ();
fd = open_trunc (fntemp);
if (fd == -1)
err (-1, "unable to create %s: ", fntemp);
if (cdb_make_start (&c, fd) == -1)
die_write ();
buffer_init (&b, buffer_unixread, STDIN_FILENO, bspace, sizeof (bspace));
while (match)
{
if (getln (&b, &line, &match, '\n') == -1)
errx (-1, "unable to read input: ");
x = line.s;
len = line.len;
if (!len)
break;
if (x[0] == '#')
continue;
if (x[0] == '\n')
continue;
while (len)
{
ch = x[len - 1];
if (ch != '\n')
if (ch != ' ')
if (ch != '\t')
break;
--len;
}
line.len = len; /* for die_bad() */
colon = byte_chr (x, len, ':');
if (colon == len)
continue;
if (!stralloc_copyb (&address, x, colon))
err (-1, "could not allocate enough memory");
if (!stralloc_copys (&data, ""))
err (-1, "could not allocate enough memory");
x += colon + 1;
len -= colon + 1;
if ((len >= 4) && byte_equal (x, 4, "deny"))
{
if (!stralloc_catb (&data, "D", 2))
err (-1, "could not allocate enough memory");
x += 4;
len -= 4;
}
else if ((len >= 5) && byte_equal (x, 5, "allow"))
{
x += 5;
len -= 5;
}
else
die_bad ();
while (len)
{
switch (*x)
{
case ',':
i = byte_chr (x, len, '=');
if (i == len)
die_bad ();
if (!stralloc_catb (&data, "+", 1))
err (-1, "could not allocate enough memory");
if (!stralloc_catb (&data, x + 1, i))
err (-1, "could not allocate enough memory");
x += i + 1;
len -= i + 1;
if (!len)
die_bad ();
ch = *x;
x += 1;
len -= 1;
i = byte_chr (x, len, ch);
if (i == len)
die_bad ();
if (!stralloc_catb (&data, x, i))
err (-1, "could not allocate enough memory");
if (!stralloc_0 (&data))
err (-1, "could not allocate enough memory");
x += i + 1;
len -= i + 1;
break;
default:
die_bad ();
}
}
doaddressdata ();
}
if (cdb_make_finish (&c) == -1)
die_write ();
if (fsync (fd) == -1)
die_write ();
if (close (fd) == -1)
die_write (); /* NFS stupidity */
if (rename (fntemp, fn))
err (-1, "unable to move %s to %s", fntemp, fn);
return 0;
}
| 8,197 |
C
|
.c
| 275 | 21.247273 | 79 | 0.478283 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,802 |
random-ip.c
|
dterweij_ndjbdns/random-ip.c
|
/*
* random-ip.c: This file is part of the `djbdns' project, originally
* written by Dr. D J Bernstein and later released under public-domain
* since late December 2007 (http://cr.yp.to/distributors.html).
*
* Copyright (C) 2009 - 2012 Prasad J Pandit
*
* This program is a free software; you can redistribute it and/or modify
* it under the terms of GNU General Public License as published by Free
* Software Foundation; either version 2 of the license or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* of FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <err.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <getopt.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "version.h"
#include "dns.h"
#include "fmt.h"
#include "scan.h"
#include "buffer.h"
char ip[4];
int ipfixed = 0;
unsigned char tab[256];
unsigned long loops = 10000;
char seed[128];
char strnum[FMT_ULONG];
static char *prog = NULL;
void
usage (void)
{
printf ("Usage: %s [OPTIONS] [NUM] [BYTE1] [BYTE2] [BYTE3]\n", prog);
printf ("\n Generate NUM random IP addresses.\n");
}
void
printh (void)
{
usage ();
printf ("\n Options:\n");
printf ("%-17s %s\n", " -h --help", "print this help");
printf ("%-17s %s\n", " -v --version", "print version information");
printf ("\nReport bugs to <[email protected]>\n");
}
int
check_option (int argc, char *argv[])
{
int n = 0, ind = 0;
const char optstr[] = "+:hv";
struct option lopt[] = \
{
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'v' },
{ 0, 0, 0, 0 }
};
opterr = optind = 0;
while ((n = getopt_long (argc, argv, optstr, lopt, &ind)) != -1)
{
switch (n)
{
case 'h':
printh ();
exit (0);
case 'v':
printf ("%s is part of djbdns version %s\n", prog, VERSION);
exit (0);
default:
errx (-1, "unknown option `%c', see: --help", optopt);
}
}
return optind;
}
int
main (int argc, char *argv[])
{
char *x = NULL;
int i = 0, j = 0;
unsigned long u = 0;
unsigned char c = 0;
prog = strdup ((x = strrchr (argv[0], '/')) != NULL ? x + 1 : argv[0]);
i = check_option (argc, argv);
argv += i;
argc -= i;
dns_random_init (seed);
for (i = 0; i < 256; i++)
tab[i] = i;
for (j = 256; j > 0; j--)
{
i = dns_random (j);
c = tab[j - 1];
tab[j - 1] = tab[i];
tab[i] = c;
}
if (*argv)
scan_ulong (*argv++, &loops);
if (*argv)
{
scan_ulong (*argv++, &u);
ip[0] = u;
ipfixed = 1;
}
if (*argv)
{
scan_ulong (*argv++, &u);
ip[1] = u;
ipfixed = 2;
}
if (*argv)
{
scan_ulong (*argv++, &u);
ip[2] = u;
ipfixed = 3;
}
if (*argv)
{
scan_ulong (*argv++, &u);
ip[3] = u;
ipfixed = 4;
}
if (ipfixed >= 1)
if (loops > 16777216)
loops = 16777216;
if (ipfixed >= 2)
if (loops > 65536)
loops = 65536;
if (ipfixed >= 3)
if (loops > 256)
loops = 256;
if (ipfixed >= 4)
if (loops > 1)
loops = 1;
while (loops)
{
u = --loops;
for (i = ipfixed; i < 4; i++)
{
ip[i] = u & 255;
u >>= 8;
}
if (ipfixed == 3)
{
c = ip[3];
ip[3] = tab[c];
}
else if (ipfixed < 3)
{
c = 0;
for (j = 0; j < 100; j++)
{
for (i = ipfixed; i < 4; i++)
{
c ^= (unsigned char) ip[i];
c = tab[c];
ip[i] = c;
}
}
}
u = (unsigned char) ip[0];
buffer_put (buffer_1, strnum, fmt_ulong (strnum, u));
buffer_puts (buffer_1, ".");
u = (unsigned char) ip[1];
buffer_put (buffer_1, strnum, fmt_ulong (strnum, u));
buffer_puts (buffer_1, ".");
u = (unsigned char) ip[2];
buffer_put (buffer_1, strnum, fmt_ulong (strnum, u));
buffer_puts (buffer_1, ".");
u = (unsigned char) ip[3];
buffer_put (buffer_1, strnum, fmt_ulong (strnum, u));
buffer_puts (buffer_1, "\n");
}
buffer_flush (buffer_1);
return 0;
}
| 4,911 |
C
|
.c
| 185 | 20.189189 | 78 | 0.517344 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,804 |
dns_transmit.c
|
dterweij_ndjbdns/dns_transmit.c
|
/*
* dns_transmit.c: This file is part of the `djbdns' project, originally
* written by Dr. D J Bernstein and later released under public-domain since
* late December 2007 (http://cr.yp.to/distributors.html).
*
* Copyright (C) 2009 - 2012 Prasad J Pandit
*
* This program is a free software; you can redistribute it and/or modify
* it under the terms of GNU General Public License as published by Free
* Software Foundation; either version 2 of the license or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* of FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <err.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "dns.h"
#include "byte.h"
#include "alloc.h"
#include "error.h"
#include "uint16.h"
#include "socket.h"
static int merge_enable;
static void (*merge_logger)(const char *, const char *, const char *);
void
dns_enable_merge (void (*f)(const char *, const char *, const char *))
{
merge_enable = 1;
merge_logger = f;
}
static int
merge_equal (struct dns_transmit *a, struct dns_transmit *b)
{
const char *ip1 = a->servers + 4 * a->curserver;
const char *ip2 = b->servers + 4 * b->curserver;
return byte_equal (ip1, 4, ip2)
&& byte_equal (a->qtype, 2, b->qtype)
&& dns_domain_equal(a->query + 14, b->query + 14);
}
struct dns_transmit *inprogress[MAXUDP];
static int
try_merge (struct dns_transmit *d)
{
int i = 0;
for (i = 0; i < MAXUDP; i++)
{
if (!inprogress[i])
continue;
if (!merge_equal(d, inprogress[i]))
continue;
d->master = inprogress[i];
inprogress[i]->slaves[inprogress[i]->nslaves++] = d;
return 1;
}
return 0;
}
static void
register_inprogress (struct dns_transmit *d)
{
int i = 0;
for (i = 0; i < MAXUDP; i++)
{
if (!inprogress[i])
{
inprogress[i] = d;
return;
}
}
errx (-1, "BUG: out of in progress slots");
}
static void
unregister_inprogress (struct dns_transmit *d)
{
int i = 0;
for (i = 0; i < MAXUDP; i++)
{
if (inprogress[i] == d)
inprogress[i] = 0;
}
}
static int
serverwantstcp (const char *buf, unsigned int len)
{
char out[12];
if (!dns_packet_copy (buf, len, 0, out, 12))
return 1;
if (out[2] & 2)
return 1;
return 0;
}
static int
serverfailed (const char *buf, unsigned int len)
{
char out[12];
unsigned int rcode = 0;
if (!dns_packet_copy (buf, len, 0, out, 12))
return 1;
rcode = out[3];
rcode &= 15;
if (rcode && (rcode != 3))
{
errno = error_again;
return 1;
}
return 0;
}
static int
irrelevant (const struct dns_transmit *d, const char *buf, unsigned int len)
{
unsigned int pos = 0;
char out[12], *dn = NULL;
if (!(pos = dns_packet_copy (buf, len, 0, out, 12)))
return 1;
if (byte_diff (out, 2, d->query + 2))
return 1;
if (out[4] != 0)
return 1;
if (out[5] != 1)
return 1;
if (!(pos = dns_packet_getname (buf, len, pos, &dn)))
return 1;
if (!dns_domain_equal (dn, d->query + 14))
{
alloc_free (dn);
return 1;
}
alloc_free (dn);
if (!(pos = dns_packet_copy (buf, len, pos, out, 4)))
return 1;
if (byte_diff (out, 2, d->qtype))
return 1;
if (byte_diff (out + 2, 2, DNS_C_IN))
return 1;
return 0;
}
static void
packetfree (struct dns_transmit *d)
{
if (!d->packet)
return;
alloc_free (d->packet);
d->packet = 0;
}
static void
mergefree (struct dns_transmit *d)
{
int i = 0;
if (merge_enable)
unregister_inprogress (d);
/* unregister us from our mater */
if (d->master)
{
for (i = 0; i < d->master->nslaves; i++)
if (d->master->slaves[i] == d)
d->master->slaves[i] = 0;
}
/* and unregister all of our slaves from us */
for (i = 0; i < d->nslaves; i++)
{
if (d->slaves[i])
d->slaves[i]->master = NULL;
}
d->nslaves = 0;
}
static void
queryfree (struct dns_transmit *d)
{
mergefree (d);
if (!d->query)
return;
alloc_free (d->query);
d->query = 0;
}
static void
socketfree (struct dns_transmit *d)
{
if (!d->s1)
return;
close (d->s1 - 1);
d->s1 = 0;
}
void
dns_transmit_free (struct dns_transmit *d)
{
queryfree (d);
socketfree (d);
packetfree (d);
}
static int
randombind (struct dns_transmit *d)
{
int j = 0;
for (j = 0; j < 10; ++j)
if (!socket_bind4 (d->s1 - 1, d->localip, 1025 + dns_random (64510)))
return 0;
if (!socket_bind4 (d->s1 - 1, d->localip, 0))
return 0;
return -1;
}
static const int timeouts[4] = { 1, 3, 11, 45 };
static int
thisudp (struct dns_transmit *d)
{
const char *ip = NULL;
socketfree (d);
mergefree (d);
while (d->udploop < 4)
{
for (; d->curserver < 16; ++d->curserver)
{
ip = d->servers + 4 * d->curserver;
if (byte_diff (ip, 4, "\0\0\0\0"))
{
if (merge_enable && try_merge (d))
{
if (merge_logger)
merge_logger (ip, d->qtype, d->query + 14);
return 0;
}
d->query[2] = dns_random (256);
d->query[3] = dns_random (256);
d->s1 = 1 + socket_udp ();
if (!d->s1)
{
dns_transmit_free (d);
return -1;
}
if (randombind (d) == -1)
{
dns_transmit_free (d);
return -1;
}
if (socket_connect4 (d->s1 - 1, ip, 53) == 0)
{
if (send (d->s1 - 1, d->query + 2, d->querylen - 2, 0)
== d->querylen - 2)
{
struct taia now;
taia_now (&now);
taia_uint (&d->deadline, timeouts[d->udploop]);
taia_add (&d->deadline, &d->deadline, &now);
d->tcpstate = 0;
if (merge_enable)
register_inprogress (d);
return 0;
}
}
socketfree (d);
}
}
++d->udploop;
d->curserver = 0;
}
dns_transmit_free (d);
return -1;
}
static int
firstudp (struct dns_transmit *d)
{
d->curserver = 0;
return thisudp (d);
}
static int
nextudp (struct dns_transmit *d)
{
++d->curserver;
return thisudp (d);
}
static int
thistcp (struct dns_transmit *d)
{
struct taia now;
const char *ip = NULL;
socketfree (d);
packetfree (d);
for (; d->curserver < 16; ++d->curserver)
{
ip = d->servers + 4 * d->curserver;
if (byte_diff (ip, 4, "\0\0\0\0"))
{
d->query[2] = dns_random (256);
d->query[3] = dns_random (256);
d->s1 = 1 + socket_tcp ();
if (!d->s1)
{
dns_transmit_free (d);
return -1;
}
if (randombind (d) == -1)
{
dns_transmit_free (d);
return -1;
}
taia_now (&now);
taia_uint (&d->deadline, 10);
taia_add (&d->deadline, &d->deadline, &now);
if (socket_connect4 (d->s1 - 1, ip, 53) == 0)
{
d->pos = 0;
d->tcpstate = 2;
return 0;
}
if (errno == error_inprogress || errno == error_wouldblock)
{
d->tcpstate = 1;
return 0;
}
socketfree(d);
}
}
dns_transmit_free(d);
return -1;
}
static int
firsttcp (struct dns_transmit *d)
{
d->curserver = 0;
return thistcp (d);
}
static int
nexttcp (struct dns_transmit *d)
{
++d->curserver;
return thistcp (d);
}
int
dns_transmit_start (struct dns_transmit *d, const char servers[64],
int flagrecursive, const char *q, const char qtype[2],
const char localip[4])
{
unsigned int len = 0;
const char s1[] = "\0\0\1\0\0\1\0\0\0\0\0\0";
const char s2[] = "\0\0\0\0\0\1\0\0\0\0\0\0gcc-bug-workaround";
dns_transmit_free (d);
errno = error_io;
len = dns_domain_length (q);
d->querylen = len + 18;
d->query = alloc (d->querylen);
if (!d->query)
return -1;
uint16_pack_big (d->query, len + 16);
byte_copy (d->query + 2, 12, flagrecursive ? s1 : s2);
byte_copy (d->query + 14, len, q);
byte_copy (d->query + 14 + len, 2, qtype);
byte_copy (d->query + 16 + len, 2, DNS_C_IN);
byte_copy (d->qtype, 2, qtype);
d->servers = servers;
byte_copy (d->localip, 4, localip);
d->udploop = flagrecursive ? 1 : 0;
if ((len + 16 > 512) || byte_equal (qtype, 2, DNS_T_ANY))
return firsttcp (d);
return firstudp (d);
}
void
dns_transmit_io (struct dns_transmit *d, iopause_fd *x, struct taia *deadline)
{
x->fd = d->s1 - 1;
switch (d->tcpstate)
{
case 0:
if (d->master)
return;
if (d->packet)
{
taia_now (deadline);
return;
}
/* otherwise, fall through */
case 3:
case 4:
case 5:
x->events = IOPAUSE_READ;
break;
case 1:
case 2:
x->events = IOPAUSE_WRITE;
}
if (taia_less (&d->deadline, deadline))
*deadline = d->deadline;
}
int
dns_transmit_get (struct dns_transmit *d, const iopause_fd *x,
const struct taia *when)
{
char udpbuf[4097];
unsigned char ch = 0;
int r = 0, fd = 0, i = 0;
fd = d->s1 - 1;
errno = error_io;
if (d->tcpstate == 0 && d->master)
return 0;
if (d->tcpstate == 0 && d->packet)
return 1;
if (!x->revents)
{
if (taia_less (when, &d->deadline))
return 0;
errno = error_timeout;
if (d->tcpstate == 0)
return nextudp (d);
return nexttcp (d);
}
if (d->tcpstate == 0)
{
/*
* have attempted to send UDP query to each server udploop times
* have sent query to curserver on UDP socket s
*/
r = recv (fd, udpbuf, sizeof (udpbuf), 0);
if (r <= 0)
{
if (errno == error_connrefused && d->udploop == 2)
return 0;
return nextudp (d);
}
if ((unsigned)r + 1 > sizeof (udpbuf))
return 0;
if (irrelevant (d, udpbuf, r))
return 0;
if (serverwantstcp (udpbuf, r))
return firsttcp (d);
if (serverfailed (udpbuf, r))
{
if (d->udploop == 2)
return 0;
return nextudp (d);
}
socketfree (d);
d->packetlen = r;
d->packet = alloc (d->packetlen);
if (!d->packet)
{
dns_transmit_free (d);
return -1;
}
byte_copy (d->packet, d->packetlen, udpbuf);
for (i = 0; i < d->nslaves; i++)
{
if (!d->slaves[i])
continue;
d->slaves[i]->packetlen = d->packetlen;
d->slaves[i]->packet = alloc(d->packetlen);
if (!d->slaves[i]->packet)
{
dns_transmit_free (d->slaves[i]);
continue;
}
byte_copy (d->slaves[i]->packet, d->packetlen, udpbuf);
}
queryfree (d);
return 1;
}
if (d->tcpstate == 1)
{
/*
* have sent connection attempt to curserver on TCP socket s
* pos not defined
*/
if (!socket_connected (fd))
return nexttcp (d);
d->pos = 0;
d->tcpstate = 2;
return 0;
}
if (d->tcpstate == 2)
{
/*
* have connection to curserver on TCP socket s have sent pos bytes
* of query
*/
r = write (fd, d->query + d->pos, d->querylen - d->pos);
if (r <= 0)
return nexttcp (d);
d->pos += r;
if (d->pos == d->querylen)
{
struct taia now;
taia_now (&now);
taia_uint (&d->deadline, 10);
taia_add (&d->deadline, &d->deadline, &now);
d->tcpstate = 3;
}
return 0;
}
if (d->tcpstate == 3)
{
/*
* have sent entire query to curserver on TCP socket s
* pos not defined
*/
r = read (fd, &ch, 1);
if (r <= 0)
return nexttcp (d);
d->packetlen = ch;
d->tcpstate = 4;
return 0;
}
if (d->tcpstate == 4)
{
/*
* have sent entire query to curserver on TCP socket s
* pos not defined
* have received one byte of packet length into packetlen
*/
r = read (fd, &ch, 1);
if (r <= 0)
return nexttcp (d);
d->pos = 0;
d->tcpstate = 5;
d->packetlen <<= 8;
d->packetlen += ch;
d->packet = alloc (d->packetlen);
if (!d->packet)
{
dns_transmit_free (d);
return -1;
}
return 0;
}
if (d->tcpstate == 5)
{
/*
* have sent entire query to curserver on TCP socket s have received
* entire packet length into packetlen packet is allocated have
* received pos bytes of packet
*/
r = read (fd, d->packet + d->pos, d->packetlen - d->pos);
if (r <= 0)
return nexttcp (d);
d->pos += r;
if (d->pos < d->packetlen)
return 0;
socketfree (d);
if (irrelevant (d, d->packet, d->packetlen))
return nexttcp(d);
if (serverwantstcp (d->packet, d->packetlen))
return nexttcp(d);
if (serverfailed (d->packet, d->packetlen))
return nexttcp(d);
queryfree(d);
return 1;
}
return 0;
}
| 14,810 |
C
|
.c
| 553 | 18.952984 | 78 | 0.501696 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,810 |
dnscache.c
|
dterweij_ndjbdns/dnscache.c
|
/*
* dnscache.c: This file is part of the `djbdns' project, originally written
* by Dr. D J Bernstein and later released under public-domain since late
* December 2007 (http://cr.yp.to/distributors.html).
*
* Copyright (C) 2009 - 2014 Prasad J Pandit
* 2012 - 2014 Frank Denis <j at pureftpd dot org>
*
* This program is a free software; you can redistribute it and/or modify
* it under the terms of GNU General Public License as published by Free
* Software Foundation; either version 2 of the license or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* of FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#define _GNU_SOURCE
#include <err.h>
#include <time.h>
#include <ctype.h>
#include <stdio.h>
#include <fcntl.h>
#include <assert.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <netinet/in.h>
#include <sys/resource.h>
#include "version.h"
#define PIDFILE "/var/run/dnscache.pid"
#define LOGFILE "/var/log/dnscache.log"
#define CFGFILE SYSCONFDIR"/ndjbdns/dnscache.conf"
static char *prog = NULL;
short mode = 0, debug_level = 0;
static uint16_t server_port = 53;
static char *cfgfile = CFGFILE, *logfile = LOGFILE, *pidfile = PIDFILE;
#include "cdb.h"
#include "dns.h"
#include "env.h"
#include "ip4.h"
#include "fmt.h"
#include "log.h"
#include "scan.h"
#include "taia.h"
#include "byte.h"
#include "open.h"
#include "query.h"
#include "alloc.h"
#include "error.h"
#include "roots.h"
#include "cache.h"
#include "ndelay.h"
#include "strerr.h"
#include "uint16.h"
#include "uint64.h"
#include "socket.h"
#include "common.h"
#include "clients.h"
#include "iopause.h"
#include "response.h"
#include "okclient.h"
#include "droproot.h"
static int
packetquery (char *buf, unsigned int len, char **q,
char qtype[2], char qclass[2], char id[2])
{
char header[12];
unsigned int pos = 0;
errno = error_proto;
pos = dns_packet_copy (buf, len, 0, header, 12);
if (!pos)
return 0;
if (header[2] & 128)
return 0; /* must not respond to responses */
if (!(header[2] & 1))
return 0; /* do not respond to non-recursive queries */
if (header[2] & 120)
return 0;
if (header[2] & 2)
return 0;
if (byte_diff (header + 4, 2, "\0\1"))
return 0;
pos = dns_packet_getname (buf, len, pos, q);
if (!pos)
return 0;
pos = dns_packet_copy (buf, len, pos, qtype, 2);
if (!pos)
return 0;
pos = dns_packet_copy (buf, len, pos, qclass, 2);
if (!pos)
return 0;
if (byte_diff (qclass, 2, DNS_C_IN) && byte_diff (qclass, 2, DNS_C_ANY))
return 0;
byte_copy (id, 2, header);
return 1;
}
uint64 numqueries = 0;
static char buf[65535];
static struct in_addr odst; /* original destination IP */
static char myipoutgoing[4];
static char myipincoming[4];
static int udp53 = 0;
static struct udpclient
{
struct query q;
struct taia start;
uint64 active; /* query number, if active; otherwise 0 */
iopause_fd *io;
char ip[4];
uint16 port;
char id[2];
} u[MAXUDP];
int uactive = 0;
void
u_drop (int j)
{
if (!u[j].active)
return;
if (debug_level > 2)
log_querydrop (u[j].active);
u[j].active = 0;
--uactive;
}
void
u_respond (int j)
{
if (!u[j].active)
return;
response_id (u[j].id);
if (response_len > 512)
response_tc ();
socket_send4 (udp53, response, response_len, u[j].ip, u[j].port, &odst);
if (debug_level)
log_querydone (u[j].active, response, response_len);
u[j].active = 0;
--uactive;
}
void
u_new (void)
{
int i = 0, j = 0, len = 0;
struct udpclient *x = NULL;
static char *q = 0;
char qtype[2], qclass[2];
for (j = 0; j < MAXUDP; j++)
if (!u[j].active)
break;
if (j >= MAXUDP)
{
j = 0;
for (i = 1; i < MAXUDP; i++)
if (taia_less (&u[i].start, &u[j].start))
j = i;
errno = error_timeout;
u_drop (j);
}
x = u + j;
taia_now (&x->start);
len = socket_recv4 (udp53, buf, sizeof (buf), x->ip, &x->port, &odst);
if (len == -1)
return;
if ((unsigned)len >= sizeof buf)
return;
if (x->port < 1024 && x->port != 53)
return;
if (!okclient (x->ip))
return;
if (!packetquery (buf, len, &q, qtype, qclass, x->id))
return;
x->active = ++numqueries;
++uactive;
if (debug_level)
log_query (x->active, x->ip, x->port, x->id, q, qtype);
switch (query_start (&x->q, q, qtype, qclass, myipoutgoing))
{
case -1:
u_drop (j);
return;
case 1:
u_respond (j);
}
}
static int tcp53 = 0;
struct tcpclient
{
struct query q;
struct taia start;
struct taia timeout;
uint64 active; /* query number or 1, if active; otherwise 0 */
iopause_fd *io;
char ip[4]; /* send response to this address */
uint16 port; /* send response to this port */
char id[2];
int tcp; /* open TCP socket, if active */
int state;
char *buf; /* 0, or dynamically allocated of length len */
unsigned int len;
unsigned int pos;
} t[MAXTCP];
int tactive = 0;
/*
* state 1: buf 0; normal state at beginning of TCP connection
* state 2: buf 0; have read 1 byte of query packet length into len
* state 3: buf allocated; have read pos bytes of buf
* state 0: buf 0; handling query in q
* state -1: buf allocated; have written pos bytes
*/
void
t_free (int j)
{
if (!t[j].buf)
return;
alloc_free (t[j].buf);
t[j].buf = 0;
}
void
t_timeout (int j)
{
struct taia now;
if (!t[j].active)
return;
taia_now (&now);
taia_uint (&t[j].timeout, 10);
taia_add (&t[j].timeout, &t[j].timeout, &now);
}
void
t_close (int j)
{
if (!t[j].active)
return;
t_free (j);
if (debug_level > 2)
log_tcpclose (t[j].ip, t[j].port);
close (t[j].tcp);
t[j].active = 0;
--tactive;
}
void
t_drop (int j)
{
if (debug_level > 2)
log_querydrop (t[j].active);
errno = error_pipe;
t_close (j);
}
void
t_respond (int j)
{
if (!t[j].active)
return;
if (debug_level)
log_querydone (t[j].active, response, response_len);
response_id (t[j].id);
t[j].len = response_len + 2;
t_free (j);
t[j].buf = alloc (response_len + 2);
if (!t[j].buf)
{
t_close (j);
return;
}
uint16_pack_big (t[j].buf, response_len);
byte_copy (t[j].buf + 2, response_len, response);
t[j].pos = 0;
t[j].state = -1;
}
void
t_rw (int j)
{
int r;
char *ch;
static char *q = 0;
unsigned int toread;
char qtype[2], qclass[2];
struct tcpclient *x = NULL;
x = t + j;
if (x->state == -1)
{
r = write (x->tcp, x->buf + x->pos, x->len - x->pos);
if (r <= 0)
{
t_close (j);
return;
}
x->pos += r;
if (x->pos == x->len)
{
t_free (j);
x->state = 1; /* could drop connection immediately */
}
return;
}
switch (x->state)
{
case 1:
toread = 2U;
break;
case 2:
toread = 1U;
break;
case 3:
toread = x->len - x->pos;
break;
default:
return; /* impossible */
}
r = read (x->tcp, buf, toread);
if (r == 0)
{
errno = error_pipe;
t_close (j);
return;
}
if (r < 0)
{
t_close (j);
return;
}
ch = buf;
if (x->state == 1)
{
x->len = (unsigned char)*ch++;
x->len <<= 8;
x->state = 2;
if (--r <= 0)
return;
}
if (x->state == 2)
{
x->len += (unsigned char)*ch;
if (x->len < 12)
{
errno = error_proto;
t_close (j);
return;
}
x->buf = alloc (x->len);
if (!x->buf)
{
t_close(j);
return;
}
x->pos = 0;
x->state = 3;
return;
}
if (x->state != 3)
return; /* impossible */
byte_copy (&x->buf[x->pos], r, ch);
x->pos += r;
if (x->pos < x->len)
return;
if (!packetquery (x->buf, x->len, &q, qtype, qclass, x->id))
{
t_close(j);
return;
}
x->active = ++numqueries;
if (debug_level)
log_query (x->active, x->ip, x->port, x->id, q, qtype);
switch (query_start (&x->q, q, qtype, qclass, myipoutgoing))
{
case -1:
t_drop (j);
return;
case 1:
t_respond (j);
return;
}
t_free (j);
x->state = 0;
}
void
t_new (void)
{
int i = 0, j = 0;
struct tcpclient *x = NULL;
for (j = 0; j < MAXTCP; ++j)
if (!t[j].active)
break;
if (j >= MAXTCP)
{
j = 0;
for (i = 1; i < MAXTCP; ++i)
if (taia_less (&t[i].start, &t[j].start))
j = i;
errno = error_timeout;
if (t[j].state == 0)
t_drop (j);
else
t_close (j);
}
x = t + j;
taia_now (&x->start);
x->tcp = socket_accept4 (tcp53, x->ip, &x->port);
if (x->tcp == -1)
return;
if (x->port < 1024 && x->port != 53)
{
close (x->tcp);
return;
}
if (!okclient (x->ip))
{
close (x->tcp);
return;
}
if (ndelay_on (x->tcp) == -1)
{
close(x->tcp);
return;
} /* Linux bug */
x->active = 1;
++tactive;
x->state = 1;
t_timeout (j);
if (debug_level > 2)
log_tcpopen (x->ip, x->port);
}
iopause_fd *udp53io = NULL;
iopause_fd *tcp53io = NULL;
iopause_fd io[3 + MAXUDP + MAXTCP];
static void
doit (void)
{
struct taia stamp;
struct taia deadline;
int j = 0, r = 0, iolen = 0;
for (;;)
{
taia_now (&stamp);
taia_uint (&deadline, 120);
taia_add (&deadline, &deadline, &stamp);
iolen = 0;
udp53io = io + iolen++;
udp53io->fd = udp53;
udp53io->events = IOPAUSE_READ;
tcp53io = io + iolen++;
tcp53io->fd = tcp53;
tcp53io->events = IOPAUSE_READ;
for (j = 0; j < MAXUDP; ++j)
{
if (u[j].active)
{
u[j].io = io + iolen++;
query_io (&u[j].q, u[j].io, &deadline);
}
}
for (j = 0; j < MAXTCP; ++j)
{
if (t[j].active)
{
t[j].io = io + iolen++;
if (t[j].state == 0)
query_io (&t[j].q, t[j].io, &deadline);
else
{
if (taia_less (&t[j].timeout, &deadline))
deadline = t[j].timeout;
t[j].io->fd = t[j].tcp;
t[j].io->events = (t[j].state > 0) ?
IOPAUSE_READ : IOPAUSE_WRITE;
}
}
}
iopause (io, iolen, &deadline, &stamp);
for (j = 0; j < MAXUDP; ++j)
{
if (u[j].active)
{
r = query_get (&u[j].q, u[j].io, &stamp);
if (r == -1)
u_drop (j);
if (r == 1)
u_respond (j);
}
}
for (j = 0; j < MAXTCP; ++j)
{
if (t[j].active)
{
if (t[j].io->revents)
t_timeout (j);
if (t[j].state == 0)
{
r = query_get (&t[j].q, t[j].io, &stamp);
if (r == -1)
t_drop (j);
if (r == 1)
t_respond (j);
}
else
if (t[j].io->revents || taia_less (&t[j].timeout, &stamp))
t_rw (j);
}
}
if (udp53io && udp53io->revents)
u_new();
if (tcp53io && tcp53io->revents)
t_new();
}
}
extern uint32 seed[32]; /* defined in common.c */
void
usage (void)
{
printf ("Usage: %s [OPTIONS]\n", prog);
}
void
printh (void)
{
usage ();
printf ("\n Options: \n");
printf ("%-17s %s\n", " -c <value>", "specify path to config file");
printf ("%-17s %s\n", " -d <value>", "print debug messages");
printf ("%-17s %s\n", " -D", "start server as daemon");
printf ("%-17s %s\n", " -l <value>", "specify path to log file");
printf ("%-17s %s\n", " -p <value>", "specify path to pid file");
printf ("%-17s %s\n", " -P <value>", "specify server port, default: 53");
printf ("\n");
printf ("%-17s %s\n", " -h --help", "print this help");
printf ("%-17s %s\n", " -v --version", "print version information");
printf ("\nReport bugs to <[email protected]>\n");
}
int
check_option (int argc, char *argv[])
{
int n = 0, ind = 0;
const char optstr[] = "+:c:d:Dl:p:P:hv";
struct option lopt[] = \
{
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'v' },
{ 0, 0, 0, 0 }
};
opterr = optind = mode = 0;
while ((n = getopt_long (argc, argv, optstr, lopt, &ind)) != -1)
{
switch (n)
{
case 'c':
cfgfile = strdup (optarg);
break;
case 'd':
mode |= DEBUG;
debug_level = atoi (optarg);
break;
case 'D':
mode |= DAEMON;
break;
case 'l':
logfile = strdup (optarg);
break;
case 'p':
pidfile = strdup (optarg);
break;
case 'P':
server_port = atoi (optarg);
break;
case 'h':
printh ();
exit (0);
case 'v':
printf ("%s version %s\n", prog, VERSION);
exit (0);
case ':':
errx (-1, "option `%c' takes an argument, see: --help", optopt);
default:
errx (-1, "unknown option `%c', see: --help", optopt);
}
}
return optind;
}
static int
dbl_init (void)
{
extern struct cdb bl; /* dns block list */
int fd = open_read ("dnsbl.cdb");
if (fd == -1)
return 0;
cdb_init (&bl, fd);
close (fd);
return 1;
}
int
main (int argc, char *argv[])
{
int i = 0;
time_t t = 0;
struct sigaction sa;
unsigned long cachesize = 0;
char *x = NULL, char_seed[128];
sa.sa_handler = handle_term;
sigaction (SIGINT, &sa, NULL);
sigaction (SIGTERM, &sa, NULL);
sa.sa_handler = SIG_IGN;
sigaction (SIGPIPE, &sa, NULL);
seed_addtime ();
seed_adduint32 (getpid ());
seed_adduint32 (getppid ());
seed_adduint32 (getuid ());
seed_adduint32 (getgid ());
seed_addtime ();
prog = strdup ((x = strrchr (argv[0], '/')) != NULL ? x + 1 : argv[0]);
i = check_option (argc, argv);
argc -= i;
argv += i;
if (mode & DAEMON)
{
i = fork ();
if (i == -1)
err (-1, "could not fork a daemon process");
if (i > 0)
return 0;
}
time (&t);
strftime (char_seed, sizeof (char_seed), "%b-%d %Y %T %Z", localtime (&t));
warnx ("version %s: starting: %s\n", VERSION, char_seed);
set_timezone ();
if (debug_level)
warnx ("TIMEZONE: %s", env_get ("TZ"));
read_conf (cfgfile);
if (!debug_level)
if ((x = env_get ("DEBUG_LEVEL")))
debug_level = atol (x);
warnx ("DEBUG_LEVEL set to `%d'", debug_level);
#ifndef __CYGWIN__
if ((x = env_get ("DATALIMIT")))
{
struct rlimit r;
unsigned long dlimit = atol (x);
if (getrlimit (RLIMIT_DATA, &r) != 0)
err (-1, "could not get resource RLIMIT_DATA");
r.rlim_cur = (dlimit <= r.rlim_max) ? dlimit : r.rlim_max;
if (setrlimit (RLIMIT_DATA, &r) != 0)
err (-1, "could not set resource RLIMIT_DATA");
if (debug_level)
warnx ("DATALIMIT set to `%ld' bytes", r.rlim_cur);
}
#endif
if (!(x = env_get ("IP")))
err (-1, "$IP not set");
if (!ip4_scan (x, myipincoming))
err (-1, "could not parse IP address `%s'", x);
seed_addtime ();
udp53 = socket_udp ();
if (udp53 == -1)
err (-1, "could not open UDP socket");
if (socket_bind4_reuse (udp53, myipincoming, server_port) == -1)
err (-1, "could not bind UDP socket");
seed_addtime ();
tcp53 = socket_tcp ();
if (tcp53 == -1)
err (-1, "could not open TCP socket");
if (socket_bind4_reuse (tcp53, myipincoming, server_port) == -1)
err (-1, "could not bind TCP socket");
if (mode & DAEMON)
{
/* redirect stdout & stderr to a log file */
redirect_to_log (logfile, STDOUT_FILENO | STDERR_FILENO);
write_pid (pidfile);
}
seed_addtime ();
droproot ();
if (mode & DAEMON)
/* crerate a new session & detach from controlling tty */
if (setsid () < 0)
err (-1, "could not start a new session for the daemon");
seed_addtime ();
socket_tryreservein (udp53, 131072);
memset (char_seed, 0, sizeof (char_seed));
for (i = 0, x = (char *)seed; (unsigned)i < sizeof (char_seed); i++, x++)
char_seed[i] = *x;
dns_random_init (char_seed);
if (!(x = env_get ("IPSEND")))
err (-1, "$IPSEND not set");
if (!ip4_scan (x, myipoutgoing))
err (-1, "could not parse IP address `%s'", x);
if (!(x = env_get ("CACHESIZE")))
err (-1, "$CACHESIZE not set");
scan_ulong (x, &cachesize);
if (!cache_init (cachesize))
err (-1, "could not allocate `%ld' bytes for cache", cachesize);
if (env_get ("HIDETTL"))
response_hidettl ();
if (env_get ("FORWARDONLY"))
query_forwardonly ();
if (env_get ("MERGEQUERIES"))
dns_enable_merge (log_merge);
if (!roots_init ())
err (-1, "could not read servers");
if (debug_level > 3)
roots_display();
if (socket_listen (tcp53, 20) == -1)
err (-1, "could not listen on TCP socket");
if (!dbl_init() && debug_level > 1)
warnx ("could not read dnsbl.cdb");
doit ();
return 0;
}
| 18,916 |
C
|
.c
| 708 | 20.09322 | 79 | 0.51369 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,812 |
socket_recv.c
|
dterweij_ndjbdns/socket_recv.c
|
/*
* socket_recv.c: This file is part of the `djbdns' project, originally
* written by Dr. D J Bernstein and later released under public-domain
* since late December 2007 (http://cr.yp.to/distributors.html).
*
* Copyright (C) 2009 - 2013 Prasad J Pandit
*
* This program is a free software; you can redistribute it and/or modify
* it under the terms of GNU General Public License as published by Free
* Software Foundation; either version 2 of the license or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* of FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <string.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "byte.h"
#include "socket.h"
/* socket_dest_ip: retrieves destination IP address from a received packet.
* This is useful on multi-home machines, wherein a server listens on the
* common address: 0.0.0.0. Returned is an IP address to which received
* packet was destined.
*/
static struct in_addr
socket_dest_ip (struct msghdr *msgh)
{
struct in_addr odst = {0};
struct cmsghdr *cmsg = NULL;
for (cmsg = CMSG_FIRSTHDR (msgh);
cmsg != NULL; cmsg = CMSG_NXTHDR (msgh, cmsg))
{
#ifdef IP_PKTINFO
if ((cmsg->cmsg_level == IPPROTO_IP)
&& (cmsg->cmsg_type == IP_PKTINFO))
{
struct in_pktinfo *p = (struct in_pktinfo *)CMSG_DATA (cmsg);
odst = p->ipi_addr;
break;
}
#elif defined IP_RECVDSTADDR
if ((cmsg->cmsg_level == IPPROTO_IP)
&& (cmsg->cmsg_type == IP_RECVDSTADDR))
{
struct in_addr *p = (struct in_addr *)CMSG_DATA (cmsg);
odst = *p;
break;
}
#endif
}
return odst;
}
int
socket_recv4 (int s, char *buf, int len, char ip[4], uint16 *port, void *odst)
{
int r = 0;
char cbuf[256];
struct iovec iov;
struct msghdr msgh;
struct sockaddr_in sa;
memset (buf, 0, len);
memset (cbuf, 0, sizeof (cbuf));
memset (&msgh, 0, sizeof (msgh));
iov.iov_len = len;
iov.iov_base = buf;
msgh.msg_iov = &iov;
msgh.msg_iovlen = 1;
msgh.msg_name = &sa;
msgh.msg_namelen = sizeof (sa);
msgh.msg_flags = 0;
msgh.msg_control = cbuf;
msgh.msg_controllen = sizeof (cbuf);
r = recvmsg (s, &msgh, 0);
if (r == -1)
return r;
byte_copy (ip, 4, (char *)&sa.sin_addr);
uint16_unpack_big ((char *)&sa.sin_port, port);
*(struct in_addr *)odst = socket_dest_ip (&msgh);
return r;
}
| 2,937 |
C
|
.c
| 89 | 28.426966 | 78 | 0.651023 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,815 |
rbldns-data.c
|
dterweij_ndjbdns/rbldns-data.c
|
/*
* rbldns-data.c: This file is part of the `ndjbdns' project, originally
* written by Dr. D J Bernstein and later released under public-domain since
* late December 2007 (http://cr.yp.to/distributors.html).
*
* Copyright (C) 2009 - 2012 Prasad J Pandit
*
* This program is a free software; you can redistribute it and/or modify
* it under the terms of GNU General Public License as published by Free
* Software Foundation; either version 2 of the license or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* of FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <err.h>
#include <stdio.h>
#include <getopt.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "version.h"
#include "fmt.h"
#include "ip4.h"
#include "byte.h"
#include "open.h"
#include "scan.h"
#include "getln.h"
#include "strerr.h"
#include "buffer.h"
#include "cdb_make.h"
#include "stralloc.h"
buffer b;
int fd = 0;
char bspace[1024];
static char *prog = NULL;
int fdcdb = 0;
struct cdb_make cdb;
static stralloc tmp;
int match = 1;
static stralloc line;
unsigned long linenum = 0;
static void
usage (void)
{
printf ("Usage: %s [OPTIONS]\n", prog);
}
static void
printh (void)
{
usage ();
printf ("\n Options:\n");
printf ("%-17s %s\n", " -h --help", "print this help");
printf ("%-17s %s\n", " -v --version", "print version information");
printf ("\nReport bugs to <[email protected]>\n");
}
static int
check_option (int argc, char *argv[])
{
int n = 0, ind = 0;
const char optstr[] = "+:hv";
struct option lopt[] = \
{
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'v' },
{ 0, 0, 0, 0 }
};
opterr = optind = 0;
while ((n = getopt_long (argc, argv, optstr, lopt, &ind)) != -1)
{
switch (n)
{
case 'h':
printh ();
exit (0);
case 'v':
printf ("%s is part of ndjbdns version %s\n", prog, VERSION);
exit (0);
default:
errx (-1, "unknown option `%c', see: --help", optopt);
}
}
return optind;
}
int
main (int argc, char *argv[])
{
char *x = NULL;
char ip[4], ch = 0;
unsigned long u = 0;
unsigned int j = 0, k = 0;
prog = strdup ((x = strrchr (argv[0], '/')) != NULL ? x + 1 : argv[0]);
j = check_option (argc, argv);
umask(022);
fd = open_read ("data");
if (fd == -1)
err (-1, "could not open file: `%s'", "data");
buffer_init (&b, buffer_unixread, fd, bspace, sizeof (bspace));
fdcdb = open_trunc ("data.tmp");
if (fdcdb == -1)
err (-1, "could not open file: `%s'", "data.tmp");
if (cdb_make_start (&cdb, fdcdb) == -1)
err (-1, "could not write to file: `%s'", "data.tmp");
while (match)
{
++linenum;
if (getln (&b, &line, &match, '\n') == -1)
err (-1, "could not read line");
while (line.len)
{
ch = line.s[line.len - 1];
if ((ch != ' ') && (ch != '\t') && (ch != '\n'))
break;
--line.len;
}
if (!line.len)
continue;
switch (line.s[0])
{
default:
err (-1, "could not parse data line: invalid leading character");
case '#':
break;
case ':':
j = byte_chr (line.s + 1, line.len - 1, ':');
if (j >= line.len - 1)
err (-1, "could not parse data line: missing colon");
if (ip4_scan (line.s + 1, ip) != j)
err (-1, "could not parse data line: malformed IP address");
if (!stralloc_copyb (&tmp, ip, 4))
err (-1, "could not allocate enough memory");
if (!stralloc_catb (&tmp, line.s + j + 2, line.len - j - 2))
err (-1, "could not allocate enough memory");
if (cdb_make_add (&cdb, "", 0, tmp.s, tmp.len) == -1)
err (-1, "could not write to file: `%s'", "data.tmp");
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
if (!stralloc_0 (&line))
err (-1, "could not allocate enough memory");
if (!stralloc_copys (&tmp, ""))
err (-1, "could not allocate enough memory");
for (j = 0; ; j++)
{
k = scan_ulong (line.s + j, &u);
if (!k)
break;
ch = u;
if (!stralloc_catb (&tmp, &ch, 1))
err (-1, "could not allocate enough memory");
j += k;
if (line.s[j] != '.')
break;
}
if (!stralloc_catb (&tmp, "\0\0\0\0", 4))
err (-1, "could not allocate enough memory");
tmp.len = 4;
if (line.s[j] == '/')
scan_ulong (line.s + j + 1, &u);
else
u = 32;
u = (u <= 32) ? u : 32;
ch = u;
if (!stralloc_catb (&tmp, &ch, 1))
err (-1, "could not allocate enough memory");
if (cdb_make_add (&cdb, tmp.s, tmp.len, "", 0) == -1)
err (-1, "could not write to file: `%s'", "data.tmp");
break;
}
}
if (cdb_make_finish (&cdb) == -1)
err (-1, "could not write to file: `%s'", "data.tmp");
if (fsync (fdcdb) == -1)
err (-1, "could not write to file: `%s'", "data.tmp");
if (close (fdcdb) == -1)
err (-1, "could not close file: `%s'", "data.tmp"); /* NFS stupidity */
if (rename ("data.tmp", "data.cdb") == -1)
err (-1, "could not move data.tmp to data.cdb");
return 0;
}
| 6,241 |
C
|
.c
| 188 | 25.829787 | 79 | 0.518765 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,820 |
walldns.c
|
dterweij_ndjbdns/walldns.c
|
/*
* walldns.c: This file is part of the `djbdns' project, originally written
* by Dr. D J Bernstein and later released under public-domain since late
* December 2007 (http://cr.yp.to/distributors.html).
*
* Copyright (C) 2009 - 2014 Prasad J Pandit
*
* This program is a free software; you can redistribute it and/or modify
* it under the terms of GNU General Public License as published by Free
* Software Foundation; either version 2 of the license or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* of FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <unistd.h>
#include "dd.h"
#include "dns.h"
#include "byte.h"
#include "common.h"
#include "response.h"
#define PIDFILE "/var/run/walldns.pid"
#define LOGFILE "/var/log/walldns.log"
#define CFGFILE SYSCONFDIR"/ndjbdns/walldns.conf"
extern short mode;
extern char *cfgfile, *logfile, *pidfile;
void
initialize (void)
{
cfgfile = cfgfile ? cfgfile : CFGFILE;
logfile = logfile ? logfile : LOGFILE;
pidfile = pidfile ? pidfile : PIDFILE;
read_conf (cfgfile);
if (mode & DAEMON)
{
/* redirect stdout & stderr to a log file */
redirect_to_log (logfile, STDOUT_FILENO | STDERR_FILENO);
write_pid (pidfile);
}
}
int
respond (char *q, char qtype[2])
{
int j = 0;
char ip[4];
int flaga = 0;
int flagptr = 0;
flaga = byte_equal (qtype, 2, DNS_T_A);
flagptr = byte_equal (qtype, 2, DNS_T_PTR);
if (byte_equal (qtype, 2, DNS_T_ANY))
flaga = flagptr = 1;
if (flaga || flagptr)
{
if (dd (q, "", ip) == 4)
{
if (flaga)
{
if (!response_rstart (q, DNS_T_A, 655360))
return 0;
if (!response_addbytes (ip, 4))
return 0;
response_rfinish (RESPONSE_ANSWER);
}
return 1;
}
j = dd (q, "\7in-addr\4arpa", ip);
if (j >= 0)
{
if (flaga && (j == 4))
{
if (!response_rstart (q, DNS_T_A, 655360))
return 0;
if (!response_addbytes (ip + 3, 1))
return 0;
if (!response_addbytes (ip + 2, 1))
return 0;
if (!response_addbytes (ip + 1, 1))
return 0;
if (!response_addbytes (ip + 0, 1))
return 0;
response_rfinish (RESPONSE_ANSWER);
}
if (flagptr)
{
if (!response_rstart (q, DNS_T_PTR, 655360))
return 0;
if (!response_addname (q))
return 0;
response_rfinish (RESPONSE_ANSWER);
}
return 1;
}
}
response[2] &= ~4;
response[3] &= ~15;
response[3] |= 5;
return 1;
}
| 3,289 |
C
|
.c
| 104 | 23.836538 | 78 | 0.56378 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,821 |
axfrdns.c
|
dterweij_ndjbdns/axfrdns.c
|
/*
* axfrdns.c: This file is part of the `djbdns' project, originally written
* by Dr. D J Bernstein and later released under public-domain since late
* December 2007 (http://cr.yp.to/distributors.html).
*
* Copyright (C) 2009 - 2014 Prasad J Pandit
*
* This program is a free software; you can redistribute it and/or modify
* it under the terms of GNU General Public License as published by Free
* Software Foundation; either version 2 of the license or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* of FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <err.h>
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <getopt.h>
#include <unistd.h>
#include <signal.h>
#include "version.h"
#include "dns.h"
#include "env.h"
#include "ip4.h"
#include "tai.h"
#include "cdb.h"
#include "str.h"
#include "log.h"
#include "byte.h"
#include "case.h"
#include "scan.h"
#include "open.h"
#include "seek.h"
#include "uint32.h"
#include "uint16.h"
#include "buffer.h"
#include "common.h"
#include "strerr.h"
#include "stralloc.h"
#include "response.h"
#include "droproot.h"
#include "timeoutread.h"
#include "timeoutwrite.h"
#define PIDFILE "/var/run/axfrdns.pid"
#define LOGFILE "/var/log/axfrdns.log"
#define CFGFILE SYSCONFDIR"/ndjbdns/axfrdns.conf"
static char *prog = NULL;
short mode = 0, debug_level = 0;
extern int respond (char *, char *, char *);
static char *cfgfile = CFGFILE, *logfile = LOGFILE, *pidfile = PIDFILE;
int
safewrite (int fd, char *buf, unsigned int len)
{
int w = 0;
w = timeoutwrite (60, fd, buf, len);
if (w <= 0)
errx (-1, "could not write to network");
return w;
}
char netwritespace[1024];
buffer netwrite = BUFFER_INIT (safewrite, 1,
netwritespace, sizeof netwritespace);
void
print (char *buf, unsigned int len)
{
char tcpheader[2];
uint16_pack_big (tcpheader, len);
buffer_put (&netwrite, tcpheader, 2);
buffer_put (&netwrite, buf, len);
buffer_flush (&netwrite);
}
char *axfr = NULL;
static char *axfrok = NULL;
void
axfrcheck (char *q)
{
int i = 0, j = 0;
if (!axfr)
return;
for (;;)
{
if (!axfr[i] || (axfr[i] == '/'))
{
if (i > j)
{
if (!dns_domain_fromdot (&axfrok, axfr + j, i - j))
err (-1, "could not allocate enough memory");
if (dns_domain_equal (q, axfrok))
return;
}
j = i + 1;
}
if (!axfr[i])
break;
++i;
}
err (-1, "zone transfer request not allowed");
}
char typeclass[4];
static char *zone;
unsigned int zonelen;
int fdcdb;
buffer bcdb;
char bcdbspace[1024];
void
get (char *buf, unsigned int len)
{
int r = 0;
while (len > 0)
{
r = buffer_get (&bcdb, buf, len);
if (r < 0)
err (-1, "could not read from file `data.cdb'");
if (!r)
err (-1, "could not read from file `data.cdb': format error");
buf += r;
len -= r;
}
}
char ip[4];
char clientloc[2];
unsigned long port;
struct tai now;
char data[32767];
uint32 dlen = 0, dpos = 0;
void
copy (char *buf, unsigned int len)
{
dpos = dns_packet_copy (data, dlen, dpos, buf, len);
if (!dpos)
err (-1, "could not read from file `data.cdb'");
}
void
doname (stralloc *sa)
{
static char *d = NULL;
dpos = dns_packet_getname (data, dlen, dpos, &d);
if (!dpos)
err (-1, "could not read from file `data.cdb'");
if (!stralloc_catb (sa, d, dns_domain_length (d)))
err (-1, "could not allocate enough memory");
}
int
build (stralloc *sa, char *q, int flagsoa, char id[2])
{
char ttl[4];
char ttd[8];
char type[2];
char misc[20];
char recordloc[2];
struct tai cutoff;
unsigned int rdatapos = 0;
dpos = 0;
copy (type, 2);
if (flagsoa)
if (byte_diff (type, 2, DNS_T_SOA))
return 0;
if (!flagsoa)
if (byte_equal (type, 2, DNS_T_SOA))
return 0;
if (!stralloc_copyb (sa, id, 2))
err (-1, "could not allocate enough memory");
if (!stralloc_catb (sa, "\204\000\0\0\0\1\0\0\0\0", 10))
err (-1, "could not allocate enough memory");
copy (misc, 1);
if ((misc[0] == '=' + 1) || (misc[0] == '*' + 1))
{
--misc[0];
copy (recordloc, 2);
if (byte_diff (recordloc, 2, clientloc))
return 0;
}
if (misc[0] == '*')
{
if (flagsoa)
return 0;
if (!stralloc_catb (sa, "\1*", 2))
err (-1, "could not allocate enough memory");
}
if (!stralloc_catb (sa, q, dns_domain_length (q)))
err (-1, "could not allocate enough memory");
if (!stralloc_catb (sa, type, 2))
err (-1, "could not allocate enough memory");
copy (ttl, 4);
copy (ttd, 8);
if (byte_diff (ttd, 8, "\0\0\0\0\0\0\0\0"))
{
tai_unpack (ttd, &cutoff);
if (byte_equal (ttl, 4, "\0\0\0\0"))
{
if (tai_less (&cutoff, &now))
return 0;
uint32_pack_big (ttl, 2);
}
else
if (!tai_less (&cutoff, &now))
return 0;
}
if (!stralloc_catb (sa, DNS_C_IN, 2))
err (-1, "could not allocate enough memory");
if (!stralloc_catb (sa, ttl, 4))
err (-1, "could not allocate enough memory");
if (!stralloc_catb(sa,"\0\0",2))
err (-1, "could not allocate enough memory");
rdatapos = sa->len;
if (byte_equal (type, 2, DNS_T_SOA))
{
doname (sa);
doname (sa);
copy (misc, 20);
if (!stralloc_catb (sa, misc, 20))
err (-1, "could not allocate enough memory");
}
else if (byte_equal (type, 2, DNS_T_NS)
|| byte_equal (type, 2, DNS_T_PTR)
|| byte_equal (type, 2, DNS_T_CNAME))
{
doname (sa);
}
else if (byte_equal (type, 2, DNS_T_MX))
{
copy (misc, 2);
if (!stralloc_catb (sa, misc, 2))
err (-1, "could not allocate enough memory");
doname (sa);
}
else
{
if (!stralloc_catb (sa, data + dpos, dlen - dpos))
err (-1, "could not allocate enough memory");
}
if (sa->len > 65535)
errx (-1, "could not read from file `data.cdb': format error");
uint16_pack_big (sa->s + rdatapos - 2, sa->len - rdatapos);
return 1;
}
static struct cdb c;
static char *q = NULL;
static stralloc soa;
static stralloc message;
void
doaxfr (char id[2])
{
int r = 0;
char num[4];
char key[512];
uint32 klen = 0;
uint32 eod = 0, pos = 0;
axfrcheck (zone);
tai_now (&now);
cdb_init (&c, fdcdb);
byte_zero (clientloc, 2);
key[0] = 0;
key[1] = '%';
byte_copy (key + 2, 4, ip);
r = cdb_find (&c, key, 6);
if (!r)
r = cdb_find (&c, key, 5);
if (!r)
r = cdb_find (&c, key, 4);
if (!r)
r = cdb_find (&c, key, 3);
if (!r)
r = cdb_find (&c, key, 2);
if (r == -1)
errx (-1, "could not read from file `data.cdb'");
if (r && (cdb_datalen (&c) == 2))
if (cdb_read (&c, clientloc, 2, cdb_datapos (&c)) == -1)
err (-1, "could not read from file `data.cdb'");
cdb_findstart (&c);
for (;;)
{
r = cdb_findnext (&c, zone, zonelen);
if (r == -1)
errx (-1, "could not read from file `data.cdb'");
if (!r)
errx (-1, "could not find information in `data.cdb'");
dlen = cdb_datalen (&c);
if (dlen > sizeof data)
errx (-1, "could not read from file `data.cdb': format error");
if (cdb_read (&c, data, dlen, cdb_datapos (&c)) == -1)
errx (-1, "could not read from file `data.cdb': format error");
if (build (&soa, zone, 1, id))
break;
}
cdb_free (&c);
print (soa.s, soa.len);
seek_begin (fdcdb);
buffer_init (&bcdb, buffer_unixread, fdcdb, bcdbspace, sizeof (bcdbspace));
pos = 0;
get (num, 4);
pos += 4;
uint32_unpack (num, &eod);
while (pos < 2048)
{
get (num, 4);
pos += 4;
}
while (pos < eod)
{
if (eod - pos < 8)
errx (-1, "could not read from file `data.cdb': format error");
get (num, 4);
pos += 4;
uint32_unpack (num, &klen);
get (num,4);
pos += 4;
uint32_unpack (num, &dlen);
if (eod - pos < klen)
errx (-1, "could not read from file `data.cdb': format error");
pos += klen;
if (eod - pos < dlen)
errx (-1, "could not read from file `data.cdb': format error");
pos += dlen;
if (klen > sizeof key)
errx (-1, "could not read from file `data.cdb': format error");
get (key, klen);
if (dlen > sizeof data)
errx (-1, "could not read from file `data.cdb': format error");
get (data, dlen);
if ((klen > 1) && (key[0] == 0))
continue; /* location */
if (klen < 1)
errx (-1, "could not read from file `data.cdb': format error");
if (dns_packet_getname (key, klen, 0, &q) != klen)
errx (-1, "could not read from file `data.cdb': format error");
if (!dns_domain_suffix (q, zone))
continue;
if (!build (&message, q, 0, id))
continue;
print (message.s, message.len);
}
print (soa.s, soa.len);
}
void
netread (char *buf, unsigned int len)
{
int r = 0;
while (len > 0)
{
r = timeoutread (60, 0, buf, len);
if (r == 0)
exit (0);
if (r < 0)
err (-1, "could not read from the network");
buf += r;
len -= r;
}
}
uint16 len;
char buf[512];
char tcpheader[2];
static char seed[128];
void
usage (void)
{
printf ("Usage: %s [OPTIONS]\n", prog);
}
void
printh (void)
{
usage ();
printf ("\n Options:\n");
printf ("%-17s %s\n", " -c <value>", "specify path to config file");
printf ("%-17s %s\n", " -d <value>", "print debug messages");
printf ("%-17s %s\n", " -D", "start server as daemon");
printf ("%-17s %s\n", " -l <value>", "specify path to log file");
printf ("%-17s %s\n", " -p <value>", "specify path to pid file");
printf ("\n");
printf ("%-17s %s\n", " -h --help", "print this help");
printf ("%-17s %s\n", " -v --version", "print version information");
printf ("\nReport bugs to <[email protected]>\n");
}
int
check_option (int argc, char *argv[])
{
int n = 0, ind = 0;
const char optstr[] = "+:c:d:Dl:p:hv";
struct option lopt[] = \
{
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'v' },
{ 0, 0, 0, 0 }
};
opterr = optind = mode = 0;
while ((n = getopt_long (argc, argv, optstr, lopt, &ind)) != -1)
{
switch (n)
{
case 'c':
cfgfile = strdup (optarg);
break;
case 'd':
mode |= DEBUG;
debug_level = atoi (optarg);
break;
case 'D':
mode |= DAEMON;
break;
case 'l':
logfile = strdup (optarg);
break;
case 'p':
pidfile = strdup (optarg);
break;
case 'h':
printh ();
exit (0);
case 'v':
printf ("%s is part of djbdns version %s\n", prog, VERSION);
exit (0);
default:
errx (-1, "unknown option `%c', see: --help", optopt);
}
}
return optind;
}
int
main (int argc, char *argv[])
{
int n = 0;
time_t t = 0;
struct sigaction sa;
char qtype[2];
char qclass[2];
char header[12];
const char *x = NULL;
unsigned int pos = 0;
unsigned long long qnum = 0;
sa.sa_handler = handle_term;
sigaction (SIGINT, &sa, NULL);
sigaction (SIGTERM, &sa, NULL);
sa.sa_handler = SIG_IGN;
sigaction (SIGPIPE, &sa, NULL);
prog = strdup ((x = strrchr (argv[0], '/')) != NULL ? x + 1 : argv[0]);
n = check_option (argc, argv);
argc -= n;
argv += n;
if (mode & DAEMON)
/* redirect stderr to a log file */
redirect_to_log (logfile, STDERR_FILENO);
time (&t);
memset (seed, 0, sizeof (seed));
strftime (seed, sizeof (seed), "%b-%d %Y %T %Z", localtime (&t));
warnx ("version %s: starting %s\n", VERSION, seed);
set_timezone ();
if (debug_level)
warnx ("TIMEZONE: %s", env_get ("TZ"));
read_conf (cfgfile);
if (!debug_level)
if ((x = env_get ("DEBUG_LEVEL")))
debug_level = atol (x);
warnx ("DEBUG_LEVEL set to `%d'", debug_level);
dns_random_init (seed);
axfr = env_get ("AXFR");
if (debug_level)
warnx ("AXFR set to `%s'", axfr);
x = env_get ("TCPREMOTEIP");
if (debug_level)
warnx ("TCPREMOTEIP set to `%s'", x);
if (x)
ip4_scan (x, ip);
else
byte_zero (ip, 4);
x = env_get ("TCPREMOTEPORT");
if (debug_level)
warnx ("TCPREMOTEPORT set to `%s'", x);
if (!x)
x = "0";
scan_ulong (x, &port);
droproot ();
for (;;)
{
netread (tcpheader, 2);
uint16_unpack_big (tcpheader, &len);
if (len > 512)
errx (-1, "excessively large request");
netread (buf, len);
pos = dns_packet_copy (buf, len, 0, header, 12);
if (!pos)
errx (-1, "truncated request");
if (header[2] & 254)
errx (-1, "bogus query");
if (header[4] || (header[5] != 1))
errx (-1, "bogus query");
pos = dns_packet_getname (buf, len, pos, &zone);
if (!pos)
errx (-1, "truncated request");
zonelen = dns_domain_length (zone);
pos = dns_packet_copy (buf, len, pos, qtype, 2);
if (!pos)
errx (-1, "truncated request");
pos = dns_packet_copy (buf, len, pos, qclass, 2);
if (!pos)
errx (-1, "truncated request");
if (byte_diff(qclass, 2, DNS_C_IN) && byte_diff(qclass, 2, DNS_C_ANY))
errx (-1, "bogus query: bad class");
log_query (++qnum, ip, port, header, zone, qtype);
if (byte_equal(qtype,2,DNS_T_AXFR))
{
case_lowerb (zone, zonelen);
fdcdb = open_read ("data.cdb");
if (fdcdb == -1)
errx (-1, "could not read from file `data.cdb'");
doaxfr (header);
close (fdcdb);
}
else
{
if (!response_query (zone, qtype, qclass))
err (-1, "could not allocate enough memory");
response[2] |= 4;
case_lowerb (zone, zonelen);
response_id (header);
response[3] &= ~128;
if (!(header[2] & 1))
response[2] &= ~1;
if (!respond (zone, qtype, ip))
errx (-1, "could not find information in file `data.cdb'");
print (response, response_len);
}
}
}
| 15,619 |
C
|
.c
| 532 | 22.742481 | 79 | 0.533333 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,850 |
siphash.h
|
dterweij_ndjbdns/siphash.h
|
/*
* siphash.h: This file is part of the `ndjbdns' project, originally written
* as 'dnscache-siphash.patch' by Mr Frank Denis.
* -> http://download.pureftpd.org/misc/dnscache-siphash.patch
*
* Copyright (c) 2012-2014 Frank Denis <j at pureftpd dot org>
*
* 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.
*/
#pragma once
int siphash24 (unsigned char *out, const unsigned char *in,
unsigned long long inlen, const unsigned char *k);
| 1,136 |
C
|
.h
| 22 | 49 | 76 | 0.761691 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,853 |
env.h
|
dterweij_ndjbdns/env.h
|
#pragma once
extern char **environ;
extern /*@null@*/char *env_get(const char *);
| 84 |
C
|
.h
| 3 | 26.333333 | 45 | 0.708861 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,855 |
roots.h
|
dterweij_ndjbdns/roots.h
|
#pragma once
extern int roots_init (void);
extern void roots_display (void);
extern int roots (char *, char *);
extern int roots_same (char *, char *);
| 156 |
C
|
.h
| 5 | 29.4 | 39 | 0.721088 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,865 |
direntry.h
|
dterweij_ndjbdns/direntry.h
|
#pragma once
/* sysdep: +dirent */
#include <sys/types.h>
#include <dirent.h>
#define direntry struct dirent
| 111 |
C
|
.h
| 5 | 20.8 | 30 | 0.75 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,876 |
prot.h
|
dterweij_ndjbdns/prot.h
|
#pragma once
extern int prot_gid (gid_t);
extern int prot_uid (uid_t);
| 72 |
C
|
.h
| 3 | 22.666667 | 28 | 0.735294 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,886 |
common.h
|
dterweij_ndjbdns/common.h
|
/*
* common.h: This file is part of the `djbdns' project, originally written
* by Dr. D J Bernstein and later released under public-domain since late
* December 2007 (http://cr.yp.to/distributors.html).
*
* Copyright (C) 2009 - 2015 Prasad J Pandit
*
* This program is a free software; you can redistribute it and/or modify
* it under the terms of GNU General Public License as published by Free
* Software Foundation; either version 2 of the license or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* of FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
#include "uint32.h"
enum op_mode { DAEMON = 1, DEBUG = 2 };
extern void seed_adduint32 (uint32);
extern void seed_addtime (void);
extern char * strtrim (const char *);
extern int check_variable (const char *);
extern void read_conf (const char *);
extern void redirect_to_log (const char *, unsigned char);
extern void write_pid (const char *);
extern void handle_term (int);
extern void set_timezone (void);
| 1,399 |
C
|
.h
| 33 | 40.424242 | 78 | 0.754062 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,802,894 |
dd.h
|
dterweij_ndjbdns/dd.h
|
#pragma once
extern int dd(const char *,const char *,char *);
| 63 |
C
|
.h
| 2 | 30 | 48 | 0.716667 |
dterweij/ndjbdns
| 2 | 30 | 0 |
GPL-2.0
|
9/7/2024, 2:33:12 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,929,158 |
touchpad_lld.c
|
petrm_ChibiOS-GFX/drivers/touchpad/XPT2046/touchpad_lld.c
|
/*
ChibiOS-LCD-Driver - Copyright (C) 2012
Joel Bodenmann aka Tectu <[email protected]>
This file is part of ChibiOS-LCD-Driver.
ChibiOS-LCD-Driver is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS-LCD-Driver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file touchpadXPT2046/touchpad_lld.c
* @brief Touchpad Driver subsystem low level driver source.
*
* @addtogroup TOUCHPAD
* @{
*/
#include "ch.h"
#include "hal.h"
#include "touchpad.h"
#if HAL_USE_TOUCHPAD || defined(__DOXYGEN__)
/*===========================================================================*/
/* Driver local definitions. */
/*===========================================================================*/
#ifdef UNUSED
#elif defined(__GNUC__)
# define UNUSED(x) UNUSED_ ## x __attribute__((unused))
#elif defined(__LCLINT__)
# define UNUSED(x) /*@unused@*/ x
#else
# define UNUSED(x) x
#endif
/*===========================================================================*/
/* Driver exported variables. */
/*===========================================================================*/
/*===========================================================================*/
/* Driver local variables. */
/*===========================================================================*/
#if !defined(__DOXYGEN__)
/* Local copy of the current touchpad driver */
static const TOUCHPADDriver *tpDriver;
static uint16_t sampleBuf[7];
#endif
/*===========================================================================*/
/* Driver local functions. */
/*===========================================================================*/
/*===========================================================================*/
/* Driver interrupt handlers. */
/*===========================================================================*/
/*===========================================================================*/
/* Driver exported functions. */
/*===========================================================================*/
/* ---- Required Routines ---- */
/**
* @brief Low level Touchpad driver initialization.
*
* @notapi
*/
void tp_lld_init(const TOUCHPADDriver *tp) {
tpDriver = tp;
if(tpDriver->direct_init)
spiStart(tpDriver->spip, tpDriver->spicfg);
}
/**
* @brief Reads a conversion from the touchpad
*
* @param[in] cmd The command bits to send to the touchpad
*
* @return The read value 12-bit right-justified
*
* @note This function only reads data, it is assumed that the pins are
* configured properly and the bus has been acquired beforehand
*
* @notapi
*/
uint16_t tp_lld_read_value(uint8_t cmd) {
static uint8_t txbuf[3] = {0};
static uint8_t rxbuf[3] = {0};
uint16_t ret;
txbuf[0] = cmd;
spiExchange(tpDriver->spip, 3, txbuf, rxbuf);
ret = (rxbuf[1] << 5) | (rxbuf[2] >> 3);
return ret;
}
/**
* @brief 7-point median filtering code for touchpad samples
*
* @note This is an internally used routine only.
*
* @notapi
*/
static void tp_lld_filter(void) {
uint16_t temp;
int i,j;
for(i = 0; i < 4; i++) {
for(j=i; j < 7; j++) {
if(sampleBuf[i] > sampleBuf[j]) {
/* Swap the values */
temp = sampleBuf[i];
sampleBuf[i] = sampleBuf[j];
sampleBuf[j] = temp;
}
}
}
}
/**
* @brief Reads out the X direction.
*
* @note The samples are median filtered for greater noise reduction
*
* @notapi
*/
uint16_t tp_lld_read_x(void) {
int i;
#if defined(SPI_USE_MUTUAL_EXCLUSION)
spiAcquireBus(tpDriver->spip);
#endif
TOUCHPAD_SPI_PROLOGUE();
palClearPad(tpDriver->spicfg->ssport, tpDriver->spicfg->sspad);
/* Discard the first conversion - very noisy and keep the ADC on hereafter
* till we are done with the sampling. Note that PENIRQ is disabled.
*/
tp_lld_read_value(0xD1);
for(i = 0; i < 7; i++) {
sampleBuf[i]=tp_lld_read_value(0xD1);
}
/* Switch on PENIRQ once again - perform a dummy read */
tp_lld_read_value(0xD0);
palSetPad(tpDriver->spicfg->ssport, tpDriver->spicfg->sspad);
TOUCHPAD_SPI_EPILOGUE();
#if defined(SPI_USE_MUTUAL_EXCLUSION)
spiReleaseBus(tpDriver->spip);
#endif
/* Find the median - use selection sort */
tp_lld_filter();
return sampleBuf[3];
}
/*
* @brief Reads out the Y direction.
*
* @notapi
*/
uint16_t tp_lld_read_y(void) {
int i;
#if defined(SPI_USE_MUTUAL_EXCLUSION)
spiAcquireBus(tpDriver->spip);
#endif
TOUCHPAD_SPI_PROLOGUE();
palClearPad(tpDriver->spicfg->ssport, tpDriver->spicfg->sspad);
/* Discard the first conversion - very noisy and keep the ADC on hereafter
* till we are done with the sampling. Note that PENIRQ is disabled.
*/
tp_lld_read_value(0x91);
for(i = 0; i < 7; i++) {
sampleBuf[i] = tp_lld_read_value(0x91);
}
/* Switch on PENIRQ once again - perform a dummy read */
tp_lld_read_value(0x90);
palSetPad(tpDriver->spicfg->ssport, tpDriver->spicfg->sspad);
TOUCHPAD_SPI_EPILOGUE();
#ifdef SPI_USE_MUTUAL_EXCLUSION
spiReleaseBus(tpDriver->spip);
#endif
/* Find the median - use selection sort */
tp_lld_filter();
return sampleBuf[3];
}
/* ---- Optional Routines ---- */
#if TOUCHPAD_HAS_IRQ || defined(__DOXYGEN__)
/*
* @brief for checking if touchpad is pressed or not.
*
* @return 1 if pressed / 0 if not pressed
*
* @notapi
*/
uint8_t tp_lld_irq(void) {
return (!palReadPad(tpDriver->tpIRQPort, tpDriver->tpIRQPin));
}
#endif
#if TOUCHPAD_HAS_PRESSURE || defined(__DOXYGEN__)
/*
* @brief Reads out the Z direction / pressure.
*
* @notapi
*/
uint16_t tp_lld_read_z(void) {
/* ToDo */
return 42;
}
#endif
#endif /* HAL_USE_TOUCHPAD */
/** @} */
| 6,704 |
C
|
.c
| 198 | 30.181818 | 80 | 0.537933 |
petrm/ChibiOS-GFX
| 2 | 14 | 0 |
GPL-3.0
|
9/7/2024, 2:34:05 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,929,160 |
touchpad_lld_config.h
|
petrm_ChibiOS-GFX/drivers/touchpad/XPT2046/touchpad_lld_config.h
|
/*
ChibiOS-LCD-Driver - Copyright (C) 2012
Joel Bodenmann aka Tectu <[email protected]>
This file is part of ChibiOS-LCD-Driver.
ChibiOS-LCD-Driver is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS-LCD-Driver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file touchpadXPT2046/touchpad_lld_config.h
* @brief Touchppad Driver subsystem low level driver.
*
* @addtogroup TOUCHPAD
* @{
*/
#ifndef _TOUCHPAD_LLD_CONFIG_H
#define _TOUCHPAD_LLD_CONFIG_H
#if HAL_USE_TOUCHPAD || defined(__DOXYGEN__)
/*===========================================================================*/
/* Driver hardware support. */
/*===========================================================================*/
#define TOUCHPAD_HAS_IRQ TRUE
#define TOUCHPAD_HAS_PRESSURE TRUE
#endif /* HAL_USE_TOUCHPAD */
#endif /* _TOUCHPAD_LLD_CONFIG_H */
/** @} */
| 1,513 |
C
|
.c
| 33 | 41.030303 | 80 | 0.606996 |
petrm/ChibiOS-GFX
| 2 | 14 | 0 |
GPL-3.0
|
9/7/2024, 2:34:05 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,929,163 |
touchpad_lld_config.h
|
petrm_ChibiOS-GFX/drivers/touchpad/ADS7843/touchpad_lld_config.h
|
/*
ChibiOS-LCD-Driver - Copyright (C) 2012
Joel Bodenmann aka Tectu <[email protected]>
This file is part of ChibiOS-LCD-Driver.
ChibiOS-LCD-Driver is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS-LCD-Driver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file touchpadADS7843/touchpad_lld_config.h
* @brief Touchpad Driver subsystem low level driver.
*
* @addtogroup TOUCHPAD
* @{
*/
#ifndef _TOUCHPAD_LLD_CONFIG_H
#define _TOUCHPAD_LLD_CONFIG_H
#if HAL_USE_TOUCHPAD || defined(__DOXYGEN__)
/*===========================================================================*/
/* Driver hardware support. */
/*===========================================================================*/
#define TOUCHPAD_HAS_IRQ TRUE
#define TOUCHPAD_HAS_PRESSURE FALSE
#endif /* HAL_USE_TOUCHPAD */
#endif /* _TOUCHPAD_LLD_CONFIG_H */
/** @} */
| 1,513 |
C
|
.c
| 33 | 41.030303 | 80 | 0.606996 |
petrm/ChibiOS-GFX
| 2 | 14 | 0 |
GPL-3.0
|
9/7/2024, 2:34:05 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,929,165 |
s6d1121_lld.c.h
|
petrm_ChibiOS-GFX/drivers/gdisp/S6D1121/s6d1121_lld.c.h
|
/*
ChibiOS/RT - Copyright (C) 2012
Joel Bodenmann aka Tectu <[email protected]>
This file is part of ChibiOS-LCD-Driver.
ChibiOS-LCD-Driver is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS-LCD-Driver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef S6D1121_H
#define S6D1121_H
// I/O assignments
#define LCD_BL_GPIO GPIOB
#define LCD_BL_PIN 8
#define LCD_CS_GPIO GPIOD
#define LCD_CS_PIN 7
#define LCD_RS_GPIO GPIOD
#define LCD_RS_PIN 11
#define LCD_RST_GPIO GPIOD
#define LCD_RST_PIN 10
#define LCD_RD_GPIO GPIOD
#define LCD_RD_PIN 9
#define LCD_WR_GPIO GPIOD
#define LCD_WR_PIN 8
#define LCD_D0_GPIO GPIOD
#define LCD_D4_GPIO GPIOE
/* all interfaces use RST via GPIO */
/* TODO: option to disable RST; assumes RST is tied high */
#define LCD_RST_LOW palClearPad(LCD_RST_GPIO, LCD_RST_PIN)
#define LCD_RST_HIGH palSetPad(LCD_RST_GPIO, LCD_RST_PIN)
#define s6d1121_delay(n) halPolledDelay(MS2RTT(n));
#if defined(LCD_USE_GPIO)
#define LCD_CS_LOW palClearPad(LCD_CS_GPIO, LCD_CS_PIN)
#define LCD_CS_HIGH palSetPad(LCD_CS_GPIO, LCD_CS_PIN)
#define LCD_RS_LOW palClearPad(LCD_RS_GPIO, LCD_RS_PIN)
#define LCD_RS_HIGH palSetPad(LCD_RS_GPIO, LCD_RS_PIN)
#define LCD_RD_LOW palClearPad(LCD_RD_GPIO, LCD_RD_PIN)
#define LCD_RD_HIGH palSetPad(LCD_RD_GPIO, LCD_RD_PIN)
#define LCD_WR_LOW palClearPad(LCD_WR_GPIO, LCD_WR_PIN)
#define LCD_WR_HIGH palSetPad(LCD_WR_GPIO, LCD_WR_PIN)
#define LCD_BL_LOW palClearPad(LCD_BL_GPIO, LCD_BL_PIN)
#define LCD_BL_HIGH palSetPad(LCD_BL_GPIO, LCD_BL_PIN)
static inline void lld_lcddelay(void) { asm volatile ("nop"); asm volatile ("nop"); }
static inline void lld_lcdwrite(uint16_t db) {
LCD_D4_GPIO->BSRR.W=((~db&0xFFF0)<<16)|(db&0xFFF0);
LCD_D0_GPIO->BSRR.W=((~db&0x000F)<<16)|(db&0x000F);
LCD_WR_LOW;
lld_lcddelay();
LCD_WR_HIGH;
}
static __inline uint16_t lld_lcdReadData(void) {
uint16_t value=0;
LCD_RS_HIGH; LCD_WR_HIGH; LCD_RD_LOW;
#ifndef STM32F4XX
// change pin mode to digital input
LCD_DATA_PORT->CRH = 0x47444444;
LCD_DATA_PORT->CRL = 0x47444444;
#endif
#ifndef STM32F4XX
// change pin mode back to digital output
LCD_DATA_PORT->CRH = 0x33333333;
LCD_DATA_PORT->CRL = 0x33333333;
#endif
LCD_RD_HIGH;
return value;
}
static __inline uint16_t lld_lcdReadReg(uint16_t lcdReg) {
uint16_t lcdRAM;
LCD_CS_LOW; LCD_RS_LOW;
lld_lcdwrite(lcdReg);
LCD_RS_HIGH;
lcdRAM = lld_lcdReadData();
LCD_CS_HIGH;
return lcdRAM;
}
static void lld_lcdWriteIndex(uint16_t lcdReg) {
LCD_RS_LOW;
lld_lcdwrite(lcdReg);
LCD_RS_HIGH;
}
static void lld_lcdWriteData(uint16_t lcdData) {
lld_lcdwrite(lcdData);
}
static void lld_lcdWriteReg(uint16_t lcdReg, uint16_t lcdRegValue) {
LCD_CS_LOW;
lld_lcdWriteIndex(lcdReg);
lld_lcdWriteData(lcdRegValue);
LCD_CS_HIGH;
}
static __inline void lld_lcdWriteStreamStart(void) {
LCD_CS_LOW;
lld_lcdWriteIndex(0x0022);
}
static __inline void lld_lcdWriteStreamStop(void) {
LCD_CS_HIGH;
}
static __inline void lld_lcdWriteStream(uint16_t *buffer, uint16_t size) {
uint16_t i;
for(i = 0; i < size; i++) { lld_lcdwrite(buffer[i]); }
}
static __inline void lld_lcdReadStreamStart(void) { /* TODO */ }
static __inline void lld_lcdReadStreamStop(void) { /* TODO */ }
static __inline void lld_lcdReadStream(uint16_t *UNUSED(buffer), size_t UNUSED(size)) { /* TODO */ }
#elif defined(LCD_USE_FSMC)
#define LCD_REG (*((volatile uint16_t *) 0x60000000)) /* RS = 0 */
#define LCD_RAM (*((volatile uint16_t *) 0x60020000)) /* RS = 1 */
static __inline void lld_lcdWriteIndex(uint16_t index) { LCD_REG = index; }
static __inline void lld_lcdWriteData(uint16_t data) { LCD_RAM = data; }
static __inline void lld_lcdWriteReg(uint16_t lcdReg,uint16_t lcdRegValue) {
LCD_REG = lcdReg;
LCD_RAM = lcdRegValue;
}
static __inline uint16_t lld_lcdReadData(void) { return (LCD_RAM); }
static __inline uint16_t lld_lcdReadReg(uint16_t lcdReg) {
LCD_REG = lcdReg;
return LCD_RAM;
}
static __inline void lld_lcdWriteStreamStart(void) { LCD_REG = 0x0022; }
static __inline void lld_lcdWriteStreamStop(void) {}
static __inline void lld_lcdWriteStream(uint16_t *buffer, uint16_t size) {
uint16_t i;
for(i = 0; i < size; i++) LCD_RAM = buffer[i];
}
static __inline void lld_lcdReadStreamStart(void) { LCD_REG = 0x0022; }
static __inline void lld_lcdReadStreamStop(void) {}
static __inline void lld_lcdReadStream(uint16_t *buffer, size_t size) {
uint16_t i;
volatile uint16_t dummy;
/* throw away first value read */
dummy = LCD_RAM;
for(i = 0; i < size; i++) buffer[i] = LCD_RAM;
}
#elif defined(LCD_USE_SPI)
#error "gdispS6d1121: LCD_USE_SPI not implemented yet"
#else
#error "gdispS6d1121: No known LCD_USE_XXX has been defined"
#endif
static void lld_lcdSetCursor(coord_t x, coord_t y) {
/* R20h - 8 bit
* R21h - 9 bit
*/
switch(GDISP.Orientation) {
case portraitInv:
lld_lcdWriteReg(0x0020, (SCREEN_WIDTH-1-x) & 0x00FF);
lld_lcdWriteReg(0x0021, (SCREEN_HEIGHT-1-y) & 0x01FF);
break;
case portrait:
lld_lcdWriteReg(0x0020, x & 0x00FF);
lld_lcdWriteReg(0x0021, y & 0x01FF);
break;
case landscape:
lld_lcdWriteReg(0x0020, y & 0x00FF);
lld_lcdWriteReg(0x0021, x & 0x01FF);
break;
case landscapeInv:
lld_lcdWriteReg(0x0020, (SCREEN_WIDTH - y - 1) & 0x00FF);
lld_lcdWriteReg(0x0021, (SCREEN_HEIGHT - x - 1) & 0x01FF);
break;
}
}
static void lld_lcdSetViewPort(uint16_t x, uint16_t y, uint16_t cx, uint16_t cy) {
/* HSA / HEA are 8 bit
* VSA / VEA are 9 bit
* use masks 0x00FF and 0x01FF to enforce this
*/
switch(GDISP.Orientation) {
case portrait:
lld_lcdWriteReg(0x46, (((x+cx-1) << 8) & 0xFF00 ) | (x & 0x00FF));
lld_lcdWriteReg(0x48, y & 0x01FF);
lld_lcdWriteReg(0x47, (y+cy-1) & 0x01FF);
break;
case landscape:
lld_lcdWriteReg(0x46, (((x+cx-1) << 8) & 0xFF00) | ((y+cy) & 0x00FF));
lld_lcdWriteReg(0x48, x & 0x01FF);
lld_lcdWriteReg(0x47, (x+cx-1) & 0x01FF);
break;
case portraitInv:
lld_lcdWriteReg(0x46, (((SCREEN_WIDTH-x-1) & 0x00FF) << 8) | ((SCREEN_WIDTH - (x+cx)) & 0x00FF));
lld_lcdWriteReg(0x48, (SCREEN_HEIGHT-(y+cy)) & 0x01FF);
lld_lcdWriteReg(0x47, (SCREEN_HEIGHT-y-1) & 0x01FF);
break;
case landscapeInv:
lld_lcdWriteReg(0x46, (((SCREEN_WIDTH - y - 1) & 0x00FF) << 8) | ((SCREEN_WIDTH - (y+cy)) & 0x00FF));
lld_lcdWriteReg(0x48, (SCREEN_HEIGHT - (x+cx)) & 0x01FF);
lld_lcdWriteReg(0x47, (SCREEN_HEIGHT - x - 1) & 0x01FF);
break;
}
lld_lcdSetCursor(x, y);
}
static void lld_lcdResetViewPort(void) {
switch(GDISP.Orientation) {
case portrait:
case portraitInv:
lld_lcdSetViewPort(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
break;
case landscape:
case landscapeInv:
lld_lcdSetViewPort(0, 0, SCREEN_HEIGHT, SCREEN_WIDTH);
break;
}
}
#endif /* S6D1121_H */
| 7,735 |
C
|
.c
| 208 | 32.990385 | 105 | 0.675117 |
petrm/ChibiOS-GFX
| 2 | 14 | 0 |
GPL-3.0
|
9/7/2024, 2:34:05 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,929,174 |
gdisp_lld_driver1.c
|
petrm_ChibiOS-GFX/drivers/gdisp/VMT/gdisp_lld_driver1.c
|
/*
ChibiOS/RT - Copyright (C) 2012
Joel Bodenmann aka Tectu <[email protected]>
This file is part of ChibiOS-LCD-Driver.
ChibiOS-LCD-Driver is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS-LCD-Driver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file gdispVMT/gdisp_lld.c
* @brief GDISP Graphics Driver subsystem low level driver source for VMT.
*
* @addtogroup GDISP
* @{
*/
#include "ch.h"
#include "hal.h"
#if HAL_USE_GDISP || defined(__DOXYGEN__)
#define CONFIGFILE() <../GDISP_VMT_NAME1()/gdisp_lld_config.h>
#define DRIVERFILE() <../GDISP_VMT_NAME1()/gdisp_lld.c>
/* We don't need these in our VMT referenced driver */
#undef GDISP_NEED_MSGAPI
#define GDISP_NEED_MSGAPI FALSE
/* Include the specific config file we want */
#include CONFIGFILE()
/* Bring in our API */
#include "gdisp.h"
/* Add the low level driver */
#include DRIVERFILE()
#endif /* HAL_USE_GDISP */
/** @} */
| 1,529 |
C
|
.c
| 38 | 35.684211 | 79 | 0.700341 |
petrm/ChibiOS-GFX
| 2 | 14 | 0 |
GPL-3.0
|
9/7/2024, 2:34:05 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,929,175 |
gdisp_lld_config.h
|
petrm_ChibiOS-GFX/drivers/gdisp/VMT/gdisp_lld_config.h
|
/*
ChibiOS/RT - Copyright (C) 2012
Joel Bodenmann aka Tectu <[email protected]>
This file is part of ChibiOS-LCD-Driver.
ChibiOS-LCD-Driver is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS-LCD-Driver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file gdispVMT/gdisp_lld_config.h
* @brief GDISP Graphic Driver subsystem low level driver header template.
*
* @addtogroup GDISP
* @{
*/
#ifndef _GDISP_LLD_CONFIG_H
#define _GDISP_LLD_CONFIG_H
#if HAL_USE_GDISP
/*===========================================================================*/
/* Driver hardware support. */
/*===========================================================================*/
#define GDISP_DRIVER_NAME "VMT"
#define GDISP_LLD(x) gdisp_lld_##x##_VMT
#define GDISP_LLD_VMT(x) (*GDISP_LLD(x))
#define GDISP_HARDWARE_LINES TRUE
#define GDISP_HARDWARE_CLEARS TRUE
#define GDISP_HARDWARE_FILLS TRUE
#define GDISP_HARDWARE_BITFILLS TRUE
#define GDISP_HARDWARE_CIRCLES TRUE
#define GDISP_HARDWARE_CIRCLEFILLS TRUE
#define GDISP_HARDWARE_ELLIPSES TRUE
#define GDISP_HARDWARE_ELLIPSEFILLS TRUE
#define GDISP_HARDWARE_ARCS TRUE
#define GDISP_HARDWARE_ARCFILLS TRUE
#define GDISP_HARDWARE_TEXT TRUE
#define GDISP_HARDWARE_TEXTFILLS TRUE
#define GDISP_HARDWARE_SCROLL TRUE
#define GDISP_HARDWARE_PIXELREAD TRUE
#define GDISP_HARDWARE_CONTROL TRUE
#define GDISP_HARDWARE_QUERY TRUE
#define GDISP_HARDWARE_CLIP TRUE
#define GDISP_SOFTWARE_TEXTFILLDRAW FALSE
#define GDISP_SOFTWARE_TEXTBLITCOLUMN FALSE
#define GDISP_PIXELFORMAT GDISP_PIXELFORMAT_RGB565
#define GDISP_PACKED_PIXELS FALSE
#define GDISP_PACKED_LINES FALSE
#endif /* HAL_USE_GDISP */
#endif /* _GDISP_LLD_CONFIG_H */
/** @} */
| 2,415 |
C
|
.c
| 56 | 39.357143 | 80 | 0.669241 |
petrm/ChibiOS-GFX
| 2 | 14 | 0 |
GPL-3.0
|
9/7/2024, 2:34:05 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,929,176 |
gdisp_lld_driver2.c
|
petrm_ChibiOS-GFX/drivers/gdisp/VMT/gdisp_lld_driver2.c
|
/*
ChibiOS/RT - Copyright (C) 2012
Joel Bodenmann aka Tectu <[email protected]>
This file is part of ChibiOS-LCD-Driver.
ChibiOS-LCD-Driver is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS-LCD-Driver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file gdispVMT/gdisp_lld.c
* @brief GDISP Graphics Driver subsystem low level driver source for VMT.
*
* @addtogroup GDISP
* @{
*/
#include "ch.h"
#include "hal.h"
#if HAL_USE_GDISP || defined(__DOXYGEN__)
#define CONFIGFILE() <../GDISP_VMT_NAME2()/gdisp_lld_config.h>
#define DRIVERFILE() <../GDISP_VMT_NAME2()/gdisp_lld.c>
/* We don't need these in our VMT referenced driver */
#undef GDISP_NEED_MSGAPI
#define GDISP_NEED_MSGAPI FALSE
/* Include the specific config file we want */
#include CONFIGFILE()
/* Bring in our API */
#include "gdisp.h"
/* Add the low level driver */
#include DRIVERFILE()
#endif /* HAL_USE_GDISP */
/** @} */
| 1,529 |
C
|
.c
| 38 | 35.684211 | 79 | 0.700341 |
petrm/ChibiOS-GFX
| 2 | 14 | 0 |
GPL-3.0
|
9/7/2024, 2:34:05 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,929,180 |
gdisp_lld_config.h
|
petrm_ChibiOS-GFX/templates/gdispXXXXX/gdisp_lld_config.h
|
/*
ChibiOS/RT - Copyright (C) 2012
Joel Bodenmann aka Tectu <[email protected]>
This file is part of ChibiOS-LCD-Driver.
ChibiOS-LCD-Driver is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS-LCD-Driver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file templates/gdisp_lld_config.h
* @brief GDISP Graphic Driver subsystem low level driver header template.
*
* @addtogroup GDISP
* @{
*/
#ifndef _GDISP_LLD_CONFIG_H
#define _GDISP_LLD_CONFIG_H
#if HAL_USE_GDISP || defined(__DOXYGEN__)
/*===========================================================================*/
/* Driver hardware support. */
/*===========================================================================*/
#define GDISP_DRIVER_NAME "YourDriverName"
#define GDISP_LLD(x) gdisp_lld_##x##_YourDriverName
#define GDISP_HARDWARE_LINES FALSE
#define GDISP_HARDWARE_CLEARS FALSE
#define GDISP_HARDWARE_FILLS FALSE
#define GDISP_HARDWARE_BITFILLS FALSE
#define GDISP_HARDWARE_CIRCLES FALSE
#define GDISP_HARDWARE_CIRCLEFILLS FALSE
#define GDISP_HARDWARE_ELLIPSES FALSE
#define GDISP_HARDWARE_ELLIPSEFILLS FALSE
#define GDISP_HARDWARE_ARCS FALSE
#define GDISP_HARDWARE_ARCFILLS FALSE
#define GDISP_HARDWARE_TEXT FALSE
#define GDISP_HARDWARE_TEXTFILLS FALSE
#define GDISP_HARDWARE_SCROLL FALSE
#define GDISP_HARDWARE_PIXELREAD FALSE
#define GDISP_HARDWARE_CONTROL FALSE
#define GDISP_HARDWARE_QUERY FALSE
#define GDISP_HARDWARE_CLIP FALSE
#define GDISP_SOFTWARE_TEXTFILLDRAW FALSE
#define GDISP_SOFTWARE_TEXTBLITCOLUMN FALSE
#define GDISP_PIXELFORMAT GDISP_PIXELFORMAT_RGB565
#define GDISP_PACKED_PIXELS FALSE
#define GDISP_PACKED_LINES FALSE
#endif /* HAL_USE_GDISP */
#endif /* _GDISP_LLD_CONFIG_H */
/** @} */
| 2,434 |
C
|
.c
| 55 | 40.454545 | 80 | 0.675032 |
petrm/ChibiOS-GFX
| 2 | 14 | 0 |
GPL-3.0
|
9/7/2024, 2:34:05 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,929,182 |
touchpad_lld.c
|
petrm_ChibiOS-GFX/templates/touchpadXXXXX/touchpad_lld.c
|
/*
ChibiOS-LCD-Driver - Copyright (C) 2012
Joel Bodenmann aka Tectu <[email protected]>
This file is part of ChibiOS-LCD-Driver.
ChibiOS-LCD-Driver is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS-LCD-Driver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file touchpadXPT2046/touchpad_lld.c
* @brief Touchpad Driver subsystem low level driver source.
*
* @addtogroup TOUCHPAD
* @{
*/
#include "ch.h"
#include "hal.h"
#include "touchpad.h"
#if HAL_USE_TOUCHPAD || defined(__DOXYGEN__)
/*===========================================================================*/
/* Driver local definitions. */
/*===========================================================================*/
/* put needed macros for your interface/driver here.
* when using SPI, macros for setting and clearing CS line
*/
#define TP_CS_HIGH palSetPad(TP_CS_PORT, TP_CS)
#define TP_CS_LOW palClearPad(TP_CS_PORT, TP_CS)
#ifdef UNUSED
#elif defined(__GNUC__)
# define UNUSED(x) UNUSED_ ## x __attribute__((unused))
#elif defined(__LCLINT__)
# define UNUSED(x) /*@unused@*/ x
#else
# define UNUSED(x) x
#endif
/*===========================================================================*/
/* Driver exported variables. */
/*===========================================================================*/
#if !defined(__DOXYGEN__)
TOUCHPADDriver Touchpad;
#endif
/*===========================================================================*/
/* Driver local variables. */
/*===========================================================================*/
/*===========================================================================*/
/* Driver local functions. */
/*===========================================================================*/
/*===========================================================================*/
/* Driver interrupt handlers. */
/*===========================================================================*/
/*===========================================================================*/
/* Driver exported functions. */
/*===========================================================================*/
/* ---- Required Routines ---- */
/**
* @brief Low level Touchpad driver initialization.
*
* @notapi
*/
void tp_lld_init(TOUCHPADDriver *tp) {
/* do communicate with the touchpad controller
* to do any inizialisation (mostly spiStart())
*/
}
/**
* @brief Reads out the X direction.
*
* @notapi
*/
uint16_t tp_lld_read_x(void) {
uint16_t x;
/* do communicate with the touchpad controller
* to receive the X-Coordinate
*/
x = 0;
return x;
}
/*
* @brief Reads out the Y direction.
*
* @notapi
*/
uint16_t tp_lld_read_y(void) {
uint16_t y;
/* do communicate with the touchpad controller
* to receive the Y-Coordinate
*/
y = 0;
return y;
}
/* ---- Optional Routines ---- */
#if TOUCHPAD_HAS_IRQ || defined(__DOXYGEN__)
/*
* @brief for checking if touchpad is pressed or not.
*
* @return 1 if pressed / 0 if not pressed
*
* @notapi
*/
uint8_t tp_lld_irq(void) {
/* do return PEN IRQ state if your
* touchpad controller does have any
*/
return 0;
}
#endif
#if TOUCHPAD_HAS_PRESSURE || defined(__DOXYGEN__)
/*
* @brief Reads out the Z direction / pressure.
*
* @notapi
*/
uint16_t tp_lld_read_z(void) {
/* return the pressure */
return 0;
}
#endif
#endif /* HAL_USE_TOUCHPAD */
/** @} */
| 4,421 |
C
|
.c
| 126 | 31.428571 | 80 | 0.468271 |
petrm/ChibiOS-GFX
| 2 | 14 | 0 |
GPL-3.0
|
9/7/2024, 2:34:05 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,929,188 |
graph.c
|
petrm_ChibiOS-GFX/old/graph/graph.c
|
/*
ChibiOS/RT - Copyright (C) 2012
Joel Bodenmann aka Tectu <[email protected]>
This file is part of ChibiOS-LCD-Driver.
ChibiOS-LCD-Driver is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS-LCD-Driver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "glcd.h"
#define MARKSIZE 5 // half
static uint16_t x, y; // origins in graph
static uint16_t grid_X, grid_Y; //grids
void graphDrawSystem(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint16_t gridX, uint16_t gridY, uint16_t color) {
uint16_t i, length;
volatile uint16_t off;
x = x0;
y = y0;
grid_X = gridX;
grid_Y = gridY;
// X-Axis
length = x1 - x0;
lcdDrawLine(x0, y0, x1, y0, color);
lcdDrawLine(x1, y0, x1-5, y0+5, color);
lcdDrawLine(x1, y0, x1-5, y0-5, color);
for(i=1; i<(length / grid_X); i++) {
off = x0 + i * grid_X;
lcdDrawLine(off, y0-MARKSIZE, off, y0+MARKSIZE, color);
}
// Y-Axis
length = y0 - y1;
lcdDrawLine(x0, y0, x0, y1, color);
lcdDrawLine(x0, y1, x0-5, y1+5, color);
lcdDrawLine(x0, y1, x0+5, y1+5, color);
for(i=1; i<(length / grid_Y); i++) {
off = y0 + i * grid_Y;
lcdDrawLine(x0-MARKSIZE, off, x0+MARKSIZE, off, color);
}
}
void graphDrawDots(int coord[][2], uint16_t entries, uint16_t radius, uint16_t color) {
uint16_t i;
for(i = 0; i < entries; i++)
lcdDrawCircle(coord[i][0]+x, y-coord[i][1], radius, 1, color);
}
void graphDrawNet(int coord[][2], uint16_t entries, uint16_t radius, uint16_t lineColor, uint16_t dotColor) {
uint16_t i;
for(i = 0; i < entries; ++i)
lcdDrawLine(coord[i-1][0]+x, y-coord[i-1][1], coord[i][0]+x, y-coord[i][1], lineColor);
for(i = 0; i < entries; ++i)
if(radius != 0)
lcdDrawCircle(coord[i][0]+x, y-coord[i][1], radius, 1, dotColor);
}
| 2,288 |
C
|
.c
| 58 | 36.258621 | 122 | 0.678265 |
petrm/ChibiOS-GFX
| 2 | 14 | 0 |
GPL-3.0
|
9/7/2024, 2:34:05 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,929,191 |
touchpad.c
|
petrm_ChibiOS-GFX/src/touchpad.c
|
/*
ChibiOS-LCD-Driver - Copyright (C) 2012
Joel Bodenmann aka Tectu <[email protected]>
This file is part of ChibiOS-LCD-Driver.
ChibiOS-LCD-Driver is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS-LCD-Driver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file touchpad.c
* @brief Touchpad Driver code.
*
* @addgroup TOUCHPAD
* @{
*/
#include "ch.h"
#include "hal.h"
#include "gdisp.h"
#include "touchpad.h"
#if HAL_USE_TOUCHPAD || defined(__DOXYGEN__)
/*===========================================================================*/
/* Driver local definitions. */
/*===========================================================================*/
#ifdef UNUSED
#elif defined(__GNUC__)
# define UNUSED(x) UNUSED_ ## x __attribute__((unused))
#elif defined(__LCLINT__)
# define UNUSED(x) /*@unused@*/ x
#else
# define UNUSED(x) x
#endif
/*===========================================================================*/
/* Driver exported variables. */
/*===========================================================================*/
/*===========================================================================*/
/* Driver local variables. */
/*===========================================================================*/
static volatile struct cal cal = {
1, 1, 0, 0
};
/*===========================================================================*/
/* Driver local functions. */
/*===========================================================================*/
/**
* @brief returns the uncalibrated readout of the X direction from the controller
*
* @noapi
*/
static uint16_t _tpReadRealX(void) {
uint32_t results = 0;
uint16_t i, x;
/* Median filtering is already done in LLD */
for(i = 0; i < CONVERSIONS; i++) {
results += tp_lld_read_x();
}
/* Take the average of the readings */
x = results / CONVERSIONS;
return x;
}
/**
* @brief return the uncalibrated readout of the Y-direction from the controller
*
* @noapi
*/
static uint16_t _tpReadRealY(void) {
uint32_t results = 0;
uint16_t i, y;
/* Median filtering is already done in LLD */
for(i = 0; i < CONVERSIONS; i++) {
results += tp_lld_read_y();
}
/* Take the average of the readings */
y = results / CONVERSIONS;
return y;
}
/**
* @brief draws a cross. Used for calibration.
*
* @noapi
*/
static void _tpDrawCross(uint16_t x, uint16_t y) {
gdispDrawLine(x-15, y, x-2, y, 0xffff);
gdispDrawLine(x+2, y, x+15, y, 0xffff);
gdispDrawLine(x, y-15, x, y-2, 0xffff);
gdispDrawLine(x, y+2, x, y+15, 0xffff);
gdispDrawLine(x-15, y+15, x-7, y+15, RGB565CONVERT(184,158,131));
gdispDrawLine(x-15, y+7, x-15, y+15, RGB565CONVERT(184,158,131));
gdispDrawLine(x-15, y-15, x-7, y-15, RGB565CONVERT(184,158,131));
gdispDrawLine(x-15, y-7, x-15, y-15, RGB565CONVERT(184,158,131));
gdispDrawLine(x+7, y+15, x+15, y+15, RGB565CONVERT(184,158,131));
gdispDrawLine(x+15, y+7, x+15, y+15, RGB565CONVERT(184,158,131));
gdispDrawLine(x+7, y-15, x+15, y-15, RGB565CONVERT(184,158,131));
gdispDrawLine(x+15, y-15, x+15, y-7, RGB565CONVERT(184,158,131));
}
/*===========================================================================*/
/* Driver exported functions. */
/*===========================================================================*/
/**
* @brief Touchpad Driver initialization.
* @note This function is NOT currently implicitly invoked by @p halInit().
* It must be called manually.
*
* @api
*/
void tpInit(const TOUCHPADDriver *tp) {
/* Initialise Mutex */
//MUTEX_INIT
/* Initialise driver */
//MUTEX_ENTER
tp_lld_init(tp);
//MUTEX_EXIT
}
/**
* @brief Get the X-Coordinate, relative to screen zero point.
*
* @return The X position in pixels.
*
* @api
*/
uint16_t tpReadX(void) {
uint16_t x, y;
x = cal.xm * _tpReadRealX() + cal.xn;
y = cal.ym * _tpReadRealY() + cal.yn;
switch(gdispGetOrientation()) {
case portrait:
return x;
case landscape:
return SCREEN_HEIGHT - y;
case portraitInv:
return SCREEN_WIDTH - x;
case landscapeInv:
return y;
}
return 0;
}
/**
* @brief Get the X-Coordinate, relative to screen zero point.
*
* @return The Y position in pixels.
*
* @api
*/
uint16_t tpReadY(void) {
uint16_t x, y;
x = cal.xm * _tpReadRealX() + cal.xn;
y = cal.ym * _tpReadRealY() + cal.yn;
switch(gdispGetOrientation()) {
case portrait:
return y;
case landscape:
return x;
case portraitInv:
return SCREEN_HEIGHT - y;
case landscapeInv:
return SCREEN_WIDTH - x;
}
return 0;
}
void tpCalibrate(void) {
const uint16_t h = gdispGetHeight();
const uint16_t w = gdispGetWidth();
const uint16_t cross[2][2] = {{(w/8), (h/8)}, {(w-(w/8)) , (h-(h/8))}};
uint16_t points[2][2];
uint8_t i;
gdispClear(Red);
gdispFillStringBox(0, 10, gdispGetWidth(), 30, "Calibration", &fontUI2Double, White, Red, justifyCenter);
for(i = 0; i < 2; i++) {
_tpDrawCross(cross[i][0], cross[i][1]);
while(!tpIRQ());
points[i][0] = _tpReadRealX();
points[i][1] = _tpReadRealY();
chThdSleepMilliseconds(100);
while(tpIRQ());
gdispFillArea(cross[i][0]-15, cross[i][1]-15, 42, 42, Red);
}
cal.xm = ((float)cross[1][0] - (float)cross[0][0]) / ((float)points[1][0] - (float)points[0][0]);
cal.ym = ((float)cross[1][1] - (float)cross[0][1]) / ((float)points[1][1] - (float)points[0][1]);
cal.xn = (float)cross[0][0] - cal.xm * (float)points[0][0];
cal.yn = (float)cross[0][1] - cal.ym * (float)points[0][1];
}
#if TOUCHPAD_HAS_IRQ || defined(__DOXYGEN__)
/**
* @brief returns if touchpad is pressed or not
*
* @return 1 if pressed, 0 otherwise
*
* @api
*/
uint8_t tpIRQ(void) {
return tp_lld_irq();
}
#endif
#if TOUCHPAD_HAS_PRESSURE || defined(__DOXYGEN__)
/**
* @brief Get the pressure.
*
* @return The pressure.
*
* @api
*/
uint16_t tpReadZ(void) {
/* ToDo */
return (tp_lld_read_z());
}
#endif
#endif /* HAL_USE_TOUCHPAD */
/** @} */
| 6,855 |
C
|
.c
| 214 | 28.911215 | 107 | 0.549272 |
petrm/ChibiOS-GFX
| 2 | 14 | 0 |
GPL-3.0
|
9/7/2024, 2:34:05 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,929,194 |
main.c
|
petrm_ChibiOS-GFX/demos/console/main.c
|
/*
ChibiOS-LCD-Driver - Copyright (C) 2012
Joel Bodenmann aka Tectu <[email protected]>
This file is part of ChibiOS-LCD-Driver.
ChibiOS-LCD-Driver is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS-LCD-Driver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ch.h"
#include "hal.h"
#include "gdisp.h"
#include "chprintf.h"
#include "console.h"
static GLCDConsole CON1;
int main(void) {
halInit();
chSysInit();
gdispInit();
gdispClear(Lime);
lcdConsoleInit(&CON1, 0, 0, gdispGetWidth(), gdispGetHeight(), &fontLarger, Black, White);
chprintf((BaseSequentialStream *)&CON1, "Hello the time is %d\nGoodbye.", chTimeNow());
while (TRUE) {
chThdSleepMilliseconds(100);
}
}
| 1,312 |
C
|
.c
| 32 | 35.625 | 92 | 0.716921 |
petrm/ChibiOS-GFX
| 2 | 14 | 0 |
GPL-3.0
|
9/7/2024, 2:34:05 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,929,195 |
main.c
|
petrm_ChibiOS-GFX/demos/notepad/main.c
|
#include "ch.h"
#include "hal.h"
#include "gdisp.h"
#include "touchpad.h"
#define COLOR_SIZE 20
#define PEN_SIZE 20
#define OFFSET 3
#define COLOR_BOX(a) (x >= a && x <= a + COLOR_SIZE)
#define PEN_BOX(a) (y >= a && y <= a + COLOR_SIZE)
#define GET_COLOR(a) (COLOR_BOX(a * COLOR_SIZE + OFFSET))
#define GET_PEN(a) (PEN_BOX(a * 2 * PEN_SIZE + OFFSET))
#define DRAW_COLOR(a) (a * COLOR_SIZE + OFFSET)
#define DRAW_PEN(a) (a * 2 * PEN_SIZE + OFFSET)
#define DRAW_AREA(x, y) (x >= PEN_SIZE + OFFSET + 3 && x <= gdispGetWidth() && \
y >= COLOR_SIZE + OFFSET + 3 && y <= gdispGetHeight())
static const SPIConfig spicfg = {
NULL,
TP_CS_PORT,
TP_CS,
/* SPI_CR1_BR_2 | */ SPI_CR1_BR_1 | SPI_CR1_BR_0,
};
TOUCHPADDriver TOUCHPADD1 = {
&SPID1,
&spicfg,
TP_IRQ_PORT,
TP_IRQ,
TRUE
};
void drawScreen(void) {
char *msg = "ChibiOS/GFX";
uint16_t colorsize = COLOR_SIZE;
uint16_t pensize = PEN_SIZE;
gdispSetOrientation(landscape);
gdispClear(White);
gdispDrawString(gdispGetWidth()-gdispGetStringWidth(msg, &fontUI2Double)-3, 3, msg, &fontUI2Double, Black);
/* colors */
gdispFillArea(0 * COLOR_SIZE + 3, 3, COLOR_SIZE, COLOR_SIZE, Black); /* Black */
gdispFillArea(1 * COLOR_SIZE + 3, 3, COLOR_SIZE, COLOR_SIZE, Red); /* Red */
gdispFillArea(2 * COLOR_SIZE + 3, 3, COLOR_SIZE, COLOR_SIZE, Yellow); /* Yellow */
gdispFillArea(3 * COLOR_SIZE + 3, 3, COLOR_SIZE, COLOR_SIZE, Green); /* Green */
gdispFillArea(4 * COLOR_SIZE + 3, 3, COLOR_SIZE, COLOR_SIZE, Blue); /* Blue */
gdispDrawBox (5 * COLOR_SIZE + 3, 3, COLOR_SIZE, COLOR_SIZE, Black); /* White */
/* pens */
gdispDrawString(OFFSET * 2, DRAW_PEN(1), "1", &fontLargeNumbers, Black);
gdispDrawString(OFFSET * 2, DRAW_PEN(2), "2", &fontLargeNumbers, Black);
gdispDrawString(OFFSET * 2, DRAW_PEN(3), "3", &fontLargeNumbers, Black);
gdispDrawString(OFFSET * 2, DRAW_PEN(4), "4", &fontLargeNumbers, Black);
gdispDrawString(OFFSET * 2, DRAW_PEN(5), "5", &fontLargeNumbers, Black);
}
int main(void) {
volatile uint16_t x, y;
color_t color = Black;
uint16_t pen = 0;
halInit();
chSysInit();
gdispInit();
tpInit(&TOUCHPADD1);
tpCalibrate();
drawScreen();
while (TRUE) {
x = tpReadX();
y = tpReadY();
/* inside color box ? */
if(y >= OFFSET && y <= COLOR_SIZE) {
if(GET_COLOR(0)) color = Black;
else if(GET_COLOR(1)) color = Red;
else if(GET_COLOR(2)) color = Yellow;
else if(GET_COLOR(3)) color = Green;
else if(GET_COLOR(4)) color = Blue;
else if(GET_COLOR(5)) color = White;
/* inside pen box ? */
} else if(x >= OFFSET && x <= PEN_SIZE) {
if(GET_PEN(1)) pen = 0;
else if(GET_PEN(2)) pen = 1;
else if(GET_PEN(3)) pen = 2;
else if(GET_PEN(4)) pen = 3;
else if(GET_PEN(5)) pen = 4;
/* inside drawing area ? */
} else if(DRAW_AREA(x, y)) {
if(pen == 0)
gdispDrawPixel(x, y, color);
else
gdispFillCircle(x, y, pen, color);
}
}
}
| 3,039 |
C
|
.c
| 86 | 31.27907 | 109 | 0.616255 |
petrm/ChibiOS-GFX
| 2 | 14 | 0 |
GPL-3.0
|
9/7/2024, 2:34:05 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,929,196 |
main.c
|
petrm_ChibiOS-GFX/demos/touchpad/main.c
|
/*
ChibiOS-LCD-Driver - Copyright (C) 2012
Joel Bodenmann aka Tectu <[email protected]>
This file is part of ChibiOS-LCD-Driver.
ChibiOS-LCD-Driver is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS-LCD-Driver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ch.h"
#include "hal.h"
#include "gdisp.h"
#include "touchpad.h"
static const SPIConfig spicfg = {
NULL, // no callback
GPIOC, // CS PORT
6, // CS PIN
SPI_CR1_BR_1 | SPI_CR1_BR_0,
};
TOUCHPADDriver TOUCHPADD1 = {
&SPID1, // SPI driver
&spicfg, // SPI config
GPIO, // IRQ PORT
4, // IRQ PIN
TRUE // start SPI
};
int main(void) {
halInit();
chSysInit();
gdispInit();
tpInit(&TOUCHPADD1);
tpCalibrate();
gdispClear(Black);
while (TRUE) {
gdispDrawPixel(tpReadX(), tpReadY(), Green);
}
}
| 1,390 |
C
|
.c
| 43 | 28.372093 | 78 | 0.690405 |
petrm/ChibiOS-GFX
| 2 | 14 | 0 |
GPL-3.0
|
9/7/2024, 2:34:05 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,929,197 |
main.c
|
petrm_ChibiOS-GFX/demos/lcd/main.c
|
/*
ChibiOS-LCD-Driver - Copyright (C) 2012
Joel Bodenmann aka Tectu <[email protected]>
This file is part of ChibiOS-LCD-Driver.
ChibiOS-LCD-Driver is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS-LCD-Driver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ch.h"
#include "hal.h"
#include "gdisp.h"
int main(void) {
halInit();
chSysInit();
gdispInit();
gdispClear(Black);
// gdispDrawXXX(...);
while (TRUE) {
chThdSleepMilliseconds(100);
}
}
| 1,035 |
C
|
.c
| 28 | 32.857143 | 78 | 0.72837 |
petrm/ChibiOS-GFX
| 2 | 14 | 0 |
GPL-3.0
|
9/7/2024, 2:34:05 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,929,216 |
gdisp_lld_board_example.h
|
petrm_ChibiOS-GFX/drivers/gdisp/Nokia6610/gdisp_lld_board_example.h
|
/*
ChibiOS/RT - Copyright (C) 2012
Joel Bodenmann aka Tectu <[email protected]>
This file is part of ChibiOS-LCD-Driver.
ChibiOS-LCD-Driver is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS-LCD-Driver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file gdispNokia6610/gdisp_lld_board_example.h
* @brief GDISP Graphic Driver subsystem board interface for the Nokia6610 display.
*
* @addtogroup GDISP
* @{
*/
#ifndef _GDISP_LLD_BOARD_H
#define _GDISP_LLD_BOARD_H
/**
* @brief Initialise the board for the display.
* @notes Performs the following functions:
* 1. initialise the spi port used by your display
* 2. initialise the reset pin (initial state not-in-reset)
* 3. initialise the chip select pin (initial state not-active)
* 4. initialise the backlight pin (initial state back-light off)
*
* @notapi
*/
static __inline void GDISP_LLD(init_board)(void) {
/* Code here */
#error "gdispNokia6610: You must supply a definition for init_board for your board"
}
/**
* @brief Set or clear the lcd reset pin.
*
* @param[in] state TRUE = lcd in reset, FALSE = normal operation
*
* @notapi
*/
static __inline void GDISP_LLD(setpin_reset)(bool_t state) {
/* Code here */
#error "gdispNokia6610: You must supply a definition for setpin_reset for your board"
}
/**
* @brief Send an 8 bit command to the lcd.
*
* @param[in] data The command to send
*
* @notapi
*/
static __inline void GDISP_LLD(write_cmd)(uint16_t data) {
/* Code here */
#error "gdispNokia6610: You must supply a definition for write_cmd for your board"
}
/**
* @brief Send an 8 bit data to the lcd.
*
* @param[in] data The data to send
*
* @notapi
*/
static __inline void GDISP_LLD(write_data)(uint16_t data) {
/* Code here */
#error "gdispNokia6610: You must supply a definition for write_data for your board"
}
#if GDISP_HARDWARE_READPIXEL || GDISP_HARDWARE_SCROLL || defined(__DOXYGEN__)
/**
* @brief Read data from the lcd.
*
* @return The data from the lcd
* @note The chip select may need to be asserted/de-asserted
* around the actual spi read
*
* @notapi
*/
static __inline uint16_t GDISP_LLD(read_data)(void) {
/* Code here */
#error "gdispNokia6610: You must supply a definition for read_data for your board"
}
#endif
#endif /* _GDISP_LLD_BOARD_H */
/** @} */
| 2,988 |
C
|
.h
| 88 | 30.386364 | 86 | 0.691586 |
petrm/ChibiOS-GFX
| 2 | 14 | 0 |
GPL-3.0
|
9/7/2024, 2:34:05 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,929,217 |
gdisp_lld_board_olimexsam7ex256.h
|
petrm_ChibiOS-GFX/drivers/gdisp/Nokia6610/gdisp_lld_board_olimexsam7ex256.h
|
/*
ChibiOS/RT - Copyright (C) 2012
Joel Bodenmann aka Tectu <[email protected]>
This file is part of ChibiOS-LCD-Driver.
ChibiOS-LCD-Driver is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS-LCD-Driver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file gdispNokia6610/gdisp_lld_board_olimexsam7ex256.h
* @brief GDISP Graphic Driver subsystem board interface for the Olimex SAM7-EX256 board.
*
* @addtogroup GDISP
* @{
*/
#ifndef _GDISP_LLD_BOARD_H
#define _GDISP_LLD_BOARD_H
// mask definitions
#define BIT0 0x00000001
#define BIT1 0x00000002
#define BIT2 0x00000004
#define BIT3 0x00000008
#define BIT4 0x00000010
#define BIT5 0x00000020
#define BIT6 0x00000040
#define BIT7 0x00000080
#define BIT8 0x00000100
#define BIT9 0x00000200
#define BIT10 0x00000400
#define BIT11 0x00000800
#define BIT12 0x00001000
#define BIT13 0x00002000
#define BIT14 0x00004000
#define BIT15 0x00008000
#define BIT16 0x00010000
#define BIT17 0x00020000
#define BIT18 0x00040000
#define BIT19 0x00080000
#define BIT20 0x00100000
#define BIT21 0x00200000
#define BIT22 0x00400000
#define BIT23 0x00800000
#define BIT24 0x01000000
#define BIT25 0x02000000
#define BIT26 0x04000000
#define BIT27 0x08000000
#define BIT28 0x10000000
#define BIT29 0x20000000
#define BIT30 0x40000000
#define BIT31 0x80000000
// ******************************************************
// Pointers to AT91SAM7X256 peripheral data structures
// ******************************************************
volatile AT91PS_PIO pPIOA = AT91C_BASE_PIOA;
volatile AT91PS_PIO pPIOB = AT91C_BASE_PIOB;
volatile AT91PS_SPI pSPI = AT91C_BASE_SPI0;
volatile AT91PS_PMC pPMC = AT91C_BASE_PMC;
volatile AT91PS_PDC pPDC = AT91C_BASE_PDC_SPI0;
/**
* @brief Initialise the board for the display.
* @notes Performs the following functions:
* 1. initialise the spi port used by your display
* 2. initialise the reset pin (initial state not-in-reset)
* 3. initialise the chip select pin (initial state not-active)
* 4. initialise the backlight pin (initial state back-light off)
*
* @notapi
*/
static __inline void GDISP_LLD(init_board)(void) {
// *********************************************************************************************
// InitSpi( )
//
// Sets up SPI channel 0 for communications to Nokia 6610 LCD Display
//
// I/O ports used: PA2 = LCD Reset (set to low to reset)
// PA12 = LCD chip select (set to low to select the LCD chip)
// PA16 = SPI0_MISO Master In - Slave Out (not used in LCD interface)
// PA17 = SPI0_MOSI Master Out - Slave In pin (Serial Data to LCD slave)
// PA18 = SPI0_SPCK Serial Clock (to LCD slave)
// PB20 = backlight control (normally PWM control, 1 = full on)
//
// *********************************************************************************************}
/* This code should really use the ChibiOS driver for these functions */
// Pin for backlight
pPIOB->PIO_CODR = PIOB_LCD_BL_MASK; // Set PB20 to LOW
pPIOB->PIO_OER = PIOB_LCD_BL_MASK; // Configure PB20 as output
// Reset pin
pPIOA->PIO_SODR = PIOA_LCD_RESET_MASK; // Set PA2 to HIGH
pPIOA->PIO_OER = PIOA_LCD_RESET_MASK; // Configure PA2 as output
// CS pin - this seems to be ignored
// pPIOA->PIO_SODR = BIT12; // Set PA2 to HIGH
// pPIOA->PIO_OER = BIT12; // Configure PA2 as output
// Init SPI0
// Disable the following pins from PIO control (will be used instead by the SPI0 peripheral)
// BIT12 = PA12 -> SPI0_NPCS0 chip select
// BIT16 = PA16 -> SPI0_MISO Master In - Slave Out (not used in LCD interface)
// BIT17 = PA17 -> SPI0_MOSI Master Out - Slave In pin (Serial Data to LCD slave)
// BIT18 = PA18 -> SPI0_SPCK Serial Clock (to LCD slave)
pPIOA->PIO_PDR = BIT12 | BIT16 | BIT17 | BIT18;
pPIOA->PIO_ASR = BIT12 | BIT16 | BIT17 | BIT18;
pPIOA->PIO_BSR = 0;
//enable the clock of SPI
pPMC->PMC_PCER = 1 << AT91C_ID_SPI0;
// Fixed mode
pSPI->SPI_CR = 0x81; //SPI Enable, Sowtware reset
pSPI->SPI_CR = 0x01; //SPI Enable
//pSPI->SPI_MR = 0xE0019; //Master mode, fixed select, disable decoder, FDIV=1 (MCK), PCS=1110
pSPI->SPI_MR = 0xE0011; //Master mode, fixed select, disable decoder, FDIV=0 (MCK), PCS=1110
//pSPI->SPI_CSR[0] = 0x01010C11; //9bit, CPOL=1, ClockPhase=0, SCLK = 48Mhz/32*12 = 125kHz
pSPI->SPI_CSR[0] = 0x01010311; //9bit, CPOL=1, ClockPhase=0, SCLK = 48Mhz/8 = 6MHz if using commented MR line above
}
/**
* @brief Set or clear the lcd reset pin.
*
* @param[in] state TRUE = lcd in reset, FALSE = normal operation
*
* @notapi
*/
static __inline void GDISP_LLD(setpin_reset)(bool_t state) {
if (state)
palClearPad(IOPORT1, PIOA_LCD_RESET);
// pPIOA->PIO_CODR = PIOA_LCD_RESET_MASK;
else
palSetPad(IOPORT1, PIOA_LCD_RESET);
// pPIOA->PIO_SODR = PIOA_LCD_RESET_MASK;
}
/**
* @brief Set or clear the lcd back-light pin.
*
* @param[in] state TRUE = lcd back-light on, FALSE = lcd back-light off
*
* @notapi
*/
static __inline void GDISP_LLD(setpin_backlight)(bool_t state) {
if (state)
palSetPad(IOPORT2, PIOB_LCD_BL);
// pPIOB->PIO_SODR = PIOB_LCD_BL_MASK;
else
palClearPad(IOPORT2, PIOB_LCD_BL);
// pPIOB->PIO_CODR = PIOB_LCD_BL_MASK;
}
/**
* @brief Send an 8 bit command to the lcd.
*
* @param[in] data The command to send
*
* @notapi
*/
static __inline void GDISP_LLD(write_cmd)(uint16_t data) {
// wait for the previous transfer to complete
while((pSPI->SPI_SR & AT91C_SPI_TXEMPTY) == 0);
// send the command
pSPI->SPI_TDR = data & 0xFF;
}
/**
* @brief Send an 8 bit data to the lcd.
*
* @param[in] data The data to send
*
* @notapi
*/
static __inline void GDISP_LLD(write_data)(uint16_t data) {
// wait for the previous transfer to complete
while((pSPI->SPI_SR & AT91C_SPI_TXEMPTY) == 0);
// send the data
pSPI->SPI_TDR = data | 0x0100;
}
#if GDISP_HARDWARE_READPIXEL || GDISP_HARDWARE_SCROLL || defined(__DOXYGEN__)
/**
* @brief Read data from the lcd.
*
* @return The data from the lcd
*
* @notapi
*/
static __inline uint16_t GDISP_LLD(read_data)(void) {
#error "gdispNokia6610: GDISP_HARDWARE_READPIXEL and GDISP_HARDWARE_SCROLL are not supported on this board"
return 0;
}
#endif
#endif /* _GDISP_LLD_BOARD_H */
/** @} */
| 7,087 |
C
|
.h
| 189 | 34.306878 | 125 | 0.655912 |
petrm/ChibiOS-GFX
| 2 | 14 | 0 |
GPL-3.0
|
9/7/2024, 2:34:05 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,933,250 |
peervpn.c
|
strfry_peervpn/peervpn.c
|
/***************************************************************************
* Copyright (C) 2016 by Tobias Volk *
* [email protected] *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
#include <signal.h>
#include <stdio.h>
#include <openssl/engine.h>
#include "ethernet/switch.c"
#include "ethernet/ndp6.c"
#include "ethernet/virtserv.c"
#include "libp2psec/p2psec.c"
#include "platform/io.c"
#include "platform/ifconfig.c"
#include "platform/seccomp.c"
#include "globals.ic"
#include "console.ic"
#include "mainloop.ic"
#include "config.ic"
#include "pwd.ic"
#include "init.ic"
// commandline parser
int main(int argc, char **argv) {
int confok;
int conffd;
int arglen;
int i;
struct s_initconfig config;
// default configuration
strcpy(config.tapname,"");
strcpy(config.ifconfig4,"");
strcpy(config.ifconfig6,"");
strcpy(config.upcmd,"");
strcpy(config.sourceip,"");
strcpy(config.sourceport,"");
strcpy(config.userstr,"");
strcpy(config.groupstr,"");
strcpy(config.chrootstr,"");
strcpy(config.networkname,"PEERVPN");
strcpy(config.initpeers,"");
strcpy(config.engines,"");
config.password_len = 0;
config.enableeth = 1;
config.enablendpcache = 0;
config.enablevirtserv = 0;
config.enablerelay = 0;
config.enableindirect = 0;
config.enableconsole = 0;
config.enableseccomp = 0;
config.forceseccomp = 0;
config.enableprivdrop = 1;
config.enableipv4 = 1;
config.enableipv6 = 1;
config.enablenat64clat = 0;
config.sockmark = 0;
setbuf(stdout,NULL);
printf("PeerVPN v%d.%03d\n", PEERVPN_VERSION_MAJOR, PEERVPN_VERSION_MINOR);
printf("(c)2016 Tobias Volk <[email protected]>\n");
printf("\n");
confok = 0;
if(argc == 2) {
arglen = 0;
for(i=0; i<3; i++) {
if(argv[1][i] == '\0') break;
arglen++;
}
if(arglen > 0) {
if(argv[1][0] == '-') {
if(!((arglen > 1) && (argv[1][1] >= '!') && (argv[1][1] <= '~'))) {
conffd = STDIN_FILENO;
parseConfigFile(conffd,&config);
confok = 1;
}
}
else {
if((conffd = (open(argv[1],O_RDONLY))) < 0) throwError("could not open config file!");
parseConfigFile(conffd,&config);
close(conffd);
confok = 1;
}
}
}
if(confok > 0) {
// start vpn node
init(&config);
}
else {
printf("usage: %s <configfile>\n", argv[0]);
}
return 0;
}
| 3,410 |
C
|
.c
| 103 | 30.699029 | 90 | 0.570561 |
strfry/peervpn
| 2 | 101 | 0 |
GPL-3.0
|
9/7/2024, 2:34:05 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,933,262 |
seccomp.c
|
strfry_peervpn/platform/seccomp.c
|
/***************************************************************************
* Copyright (C) 2014 by Tobias Volk *
* [email protected] *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
#ifndef F_SECCOMP_C
#define F_SECCOMP_C
#ifdef SECCOMP_ENABLE
#include <seccomp.h>
// Defines and loads seccomp filter. Returns 1 on success.
static int seccompEnableDo(scmp_filter_ctx ctx) {
if(ctx == NULL) { return 0; }
if(seccomp_reset(ctx, SCMP_ACT_KILL) != 0) { return 0; }
if(seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(read), 0) != 0) { return 0; }
if(seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(write), 0) != 0) { return 0; }
if(seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(recvfrom), 0) != 0) { return 0; }
if(seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(sendto), 0) != 0) { return 0; }
if(seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(time), 0) != 0) { return 0; }
if(seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(select), 0) != 0) { return 0; }
#ifdef __NR__newselect
if(seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(_newselect), 0) != 0) { return 0; }
#endif
#ifdef __NR_sigreturn
if(seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(sigreturn), 0) != 0) { return 0; }
#endif
if(seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(rt_sigreturn), 0) != 0) { return 0; }
if(seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(restart_syscall), 0) != 0) { return 0; }
if(seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(close), 0) != 0) { return 0; }
if(seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(exit), 0) != 0) { return 0; }
if(seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(exit_group), 0) != 0) { return 0; }
if(seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(brk), 0) != 0) { return 0; }
if(seccomp_rule_add(ctx, SCMP_ACT_ERRNO(ENOSYS), SCMP_SYS(munmap), 0) != 0) { return 0; }
if(seccomp_load(ctx) != 0) { return 0; }
return 1;
}
// Enables seccomp filtering. Returns 1 on success.
static int seccompEnable() {
int enabled;
scmp_filter_ctx filter;
filter = seccomp_init(SCMP_ACT_KILL);
if(filter != NULL) {
enabled = seccompEnableDo(filter);
seccomp_release(filter);
return enabled;
}
return 0;
}
#else
// No seccomp support.
static int seccompEnable() {
return 0;
}
#endif
#endif // F_SECCOMP_C
| 3,381 |
C
|
.c
| 66 | 49.090909 | 91 | 0.57221 |
strfry/peervpn
| 2 | 101 | 0 |
GPL-3.0
|
9/7/2024, 2:34:05 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,933,265 |
idsp.c
|
strfry_peervpn/libp2psec/idsp.c
|
/***************************************************************************
* Copyright (C) 2015 by Tobias Volk *
* [email protected] *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
#ifndef F_IDSP_C
#define F_IDSP_C
#include <stdlib.h>
#define idsp_ALIGN_BOUNDARY 16
struct s_idsp {
int *idfwd;
int *idlist;
int count;
int used;
int iter;
};
static void idspReset(struct s_idsp *idsp) {
int i;
for(i=0; i<idsp->count; i++) {
idsp->idfwd[i] = -1;
idsp->idlist[i] = i;
}
idsp->used = 0;
idsp->iter = 0;
}
static int idspMemSize(const int size) {
const int align_boundary = idsp_ALIGN_BOUNDARY;
int memsize;
memsize = 0;
memsize = memsize + ((((sizeof(struct s_idsp)) + (align_boundary - 1)) / align_boundary) * align_boundary); // struct
memsize = memsize + ((((sizeof(int) * size) + (align_boundary - 1)) / align_boundary) * align_boundary); // idfwd_mem
memsize = memsize + ((((sizeof(int) * size) + (align_boundary - 1)) / align_boundary) * align_boundary); // idlist_mem
return memsize;
}
static int idspMemInit(struct s_idsp *idsp, const int mem_size, const int size) {
const int align_boundary = idsp_ALIGN_BOUNDARY;
const int idfwd_mem_offset = ((((sizeof(struct s_idsp)) + (align_boundary - 1)) / align_boundary) * align_boundary);
const int idlist_mem_offset = idfwd_mem_offset + ((((sizeof(int) * size) + (align_boundary - 1)) / align_boundary) * align_boundary);
const int min_mem_size = idlist_mem_offset + ((((sizeof(int) * size) + (align_boundary - 1)) / align_boundary) * align_boundary);
unsigned char *idsp_mem;
idsp_mem = (unsigned char *)idsp;
if(min_mem_size == idspMemSize(size)) {
if(size > 0 && mem_size >= min_mem_size) {
idsp->idfwd = (int *)(&idsp_mem[idfwd_mem_offset]);
idsp->idlist = (int *)(&idsp_mem[idlist_mem_offset]);
idsp->count = size;
idspReset(idsp);
return 1;
}
}
return 0;
}
static int idspCreate(struct s_idsp *idsp, const int size) {
int *idfwd_mem;
int *idlist_mem;
idfwd_mem = NULL;
idlist_mem = NULL;
if(size > 0) {
idfwd_mem = malloc(sizeof(int) * size);
if(idfwd_mem != NULL) {
idlist_mem = malloc(sizeof(int) * size);
if(idlist_mem != NULL) {
idsp->idfwd = idfwd_mem;
idsp->idlist = idlist_mem;
idsp->count = size;
idspReset(idsp);
return 1;
}
free(idfwd_mem);
}
}
return 0;
}
static int idspNextN(struct s_idsp *idsp, const int start) {
int nextid;
int iter;
int used;
int pos;
used = idsp->used;
if(used > 0) {
if(!(start < 0) && (start < idsp->count)) {
pos = start;
}
else {
pos = 0;
}
iter = idsp->idfwd[pos];
if(iter < 0) {
iter = 0;
}
nextid = idsp->idlist[((iter + 1) % used)];
return nextid;
}
return -1;
}
static int idspNext(struct s_idsp *idsp) {
int iter;
int used;
iter = idsp->iter;
used = idsp->used;
if(used > 0) {
if(!(iter < used)) { iter = 0; }
idsp->iter = (iter + 1);
return idsp->idlist[iter];
}
return -1;
}
/*
static int idspNext(struct s_idsp *idsp) {
int iter;
int used;
iter = idsp->iter;
used = idsp->used;
if(used > 0) {
if(!(iter < used)) { iter = 0; }
idsp->iter = (iter + 1);
return idsp->idlist[iter];
}
else {
return -1;
}
}
*/
static int idspNew(struct s_idsp *idsp) {
int new_id;
int new_pos;
if(idsp->used < idsp->count) {
new_pos = idsp->used++;
new_id = idsp->idlist[new_pos];
idsp->idfwd[new_id] = new_pos;
return new_id;
}
else {
return -1;
}
}
static int idspGetPos(struct s_idsp *idsp, const int id) {
if((id >= 0) && (id < idsp->count)) {
return idsp->idfwd[id];
}
else {
return -1;
}
}
static void idspDelete(struct s_idsp *idsp, const int id) {
int pos;
int swp_id;
int swp_pos;
pos = idspGetPos(idsp, id);
if(!(pos < 0)) {
idsp->idfwd[id] = -1;
swp_pos = --idsp->used;
if(swp_pos != pos) {
swp_id = idsp->idlist[swp_pos];
idsp->idlist[swp_pos] = id;
idsp->idlist[pos] = swp_id;
idsp->idfwd[swp_id] = pos;
}
}
}
static int idspIsValid(struct s_idsp *idsp, const int id) {
return (!(idspGetPos(idsp, id) < 0));
}
static int idspUsedCount(struct s_idsp *idsp) {
return idsp->used;
}
static int idspSize(struct s_idsp *idsp) {
return idsp->count;
}
static void idspDestroy(struct s_idsp *idsp) {
idsp->used = 0;
idsp->count = 0;
free(idsp->idlist);
free(idsp->idfwd);
}
#endif // F_IDSP_C
| 5,461 |
C
|
.c
| 188 | 26.611702 | 134 | 0.58483 |
strfry/peervpn
| 2 | 101 | 0 |
GPL-3.0
|
9/7/2024, 2:34:05 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,933,274 |
rsa.c
|
strfry_peervpn/libp2psec/rsa.c
|
/***************************************************************************
* Copyright (C) 2013 by Tobias Volk *
* [email protected] *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
#ifndef F_RSA_C
#define F_RSA_C
#include "crypto.c"
#include <openssl/evp.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/bn.h>
// Minimum size of DER encoded RSA public key in bytes.
#define rsa_MINSIZE 48
// Maximum size of DER encoded RSA public key in bytes.
#define rsa_MAXSIZE 416
// The RSA structure.
struct s_rsa {
int isvalid;
int isprivate;
EVP_PKEY *key;
EVP_MD_CTX *md;
BIGNUM *bn;
};
// Returns 1 if RSA structure contains a valid public key
static int rsaIsValid(const struct s_rsa *rsa) {
return rsa->isvalid;
}
// Returns 1 if RSA structure contains a private key
static int rsaIsPrivate(const struct s_rsa *rsa) {
return rsa->isprivate;
}
// Get size of DER encoded public key.
static int rsaGetDERSize(const struct s_rsa *rsa) {
int len = i2d_PublicKey(rsa->key, NULL);
if(len > 0) {
return len;
}
else {
return 0;
}
}
// Get DER encoded public key. Returns length if successful.
static int rsaGetDER(unsigned char *buf, const int buf_size, const struct s_rsa *rsa) {
unsigned char *i2dbuf;
int len;
int ptlen = rsaGetDERSize(rsa);
i2dbuf = buf;
if((ptlen > rsa_MINSIZE) && (ptlen < buf_size)) {
len = i2d_PublicKey(rsa->key, &i2dbuf);
if(len > 0) {
return len;
}
else {
return 0;
}
}
else {
return 0;
}
}
// Get SHA-256 fingerprint of public key
static int rsaGetFingerprint(unsigned char *buf, const int buf_size, const struct s_rsa *rsa) {
unsigned char derbuf[rsa_MAXSIZE];
int dersize = rsaGetDER(derbuf, rsa_MAXSIZE, rsa);
if(dersize > 0) {
return cryptoCalculateSHA256(buf, buf_size, derbuf, dersize);
}
else {
return 0;
}
}
// Generate RSA public/private key pair
static int rsaGenerate(struct s_rsa *rsa, const int key_size) {
RSA *rsakey;
rsa->isvalid = 0;
if(key_size > 0) {
rsakey = RSA_new();
if(rsakey != NULL) {
if(BN_set_word(rsa->bn, RSA_F4)) {
if(RSA_generate_key_ex(rsakey, key_size, rsa->bn, NULL)) {
if(RSA_check_key(rsakey) == 1) {
if(EVP_PKEY_assign_RSA(rsa->key, rsakey)) {
rsa->isvalid = 1;
rsa->isprivate = 1;
return 1;
}
}
}
BN_zero(rsa->bn);
}
RSA_free(rsakey);
}
}
return 0;
}
// Load DER encoded public key.
static int rsaLoadDER(struct s_rsa *rsa, const unsigned char *pubkey, const int pubkey_size) {
EVP_PKEY *d2ipkey;
const unsigned char *d2ikey;
rsa->isvalid = 0;
if((pubkey_size > rsa_MINSIZE) && (pubkey != NULL)) {
d2ikey = pubkey;
d2ipkey = rsa->key;
if(d2i_PublicKey(EVP_PKEY_RSA, &d2ipkey, &d2ikey, pubkey_size) != NULL) {
rsa->isvalid = 1;
rsa->isprivate = 0;
return 1;
}
else {
return 0;
}
}
else {
return 0;
}
}
// Load PEM encoded public key.
static int rsaLoadPEM(struct s_rsa *rsa, unsigned char *pubkey, const int pubkey_size) {
BIO *biopub;
RSA *rsakey;
int ret;
rsa->isvalid = 0;
if((pubkey_size > 0) && (pubkey != NULL)) {
ret = 0;
biopub = BIO_new_mem_buf(pubkey, pubkey_size);
if(biopub != NULL) {
rsakey = RSA_new();
if(rsakey != NULL) {
if(PEM_read_bio_RSA_PUBKEY(biopub, &rsakey, NULL, NULL) != NULL) {
EVP_PKEY_assign_RSA(rsa->key, rsakey);
rsa->isvalid = 1;
rsa->isprivate = 0;
ret = 1;
}
else {
RSA_free(rsakey);
}
}
BIO_free(biopub);
}
return ret;
}
else {
return 0;
}
}
// Load PEM encoded private key.
static int rsaLoadPrivatePEM(struct s_rsa *rsa, unsigned char *privkey, const int privkey_size) {
BIO *biopriv;
RSA *rsakey;
int ret;
rsa->isvalid = 0;
if((privkey_size > 0) && (privkey != NULL)) {
ret = 0;
biopriv = BIO_new_mem_buf(privkey, privkey_size);
if(biopriv != NULL) {
rsakey = RSA_new();
if(rsakey != NULL) {
if(PEM_read_bio_RSAPrivateKey(biopriv, &rsakey, NULL, NULL) != NULL) {
if(RSA_check_key(rsakey) == 1) {
EVP_PKEY_assign_RSA(rsa->key, rsakey);
rsa->isvalid = 1;
rsa->isprivate = 1;
ret = 1;
}
else {
RSA_free(rsakey);
}
}
else {
RSA_free(rsakey);
}
}
BIO_free(biopriv);
}
return ret;
}
else {
return 0;
}
}
// Return maximum size of a signature.
static int rsaSignSize(const struct s_rsa *rsa) {
return EVP_PKEY_size(rsa->key);
}
// Generate signature. Returns length of signature if successful.
static int rsaSign(struct s_rsa *rsa, unsigned char *sign_buf, const int sign_len, const unsigned char *in_buf, const int in_len) {
int sign_maxlen = rsaSignSize(rsa);
int len;
if(sign_len < sign_maxlen) return 0;
if(!EVP_SignInit_ex(rsa->md, EVP_sha256(), NULL)) return 0;
if(!EVP_SignUpdate(rsa->md, in_buf, in_len)) return 0;
if(!EVP_SignFinal(rsa->md, sign_buf, (unsigned int *)&len, rsa->key)) return 0;
if(!(len > 0)) return 0;
return len;
}
// Verify signature. Returns 1 if successful.
static int rsaVerify(struct s_rsa *rsa, const unsigned char *sign_buf, const int sign_len, const unsigned char *in_buf, const int in_len) {
if(!EVP_VerifyInit_ex(rsa->md, EVP_sha256(), NULL)) return 0;
if(!EVP_VerifyUpdate(rsa->md, in_buf, in_len)) return 0;
if(!EVP_VerifyFinal(rsa->md, sign_buf, sign_len, rsa->key)) return 0;
return 1;
}
// Reset a RSA object.
static void rsaReset(struct s_rsa *rsa) {
rsa->isvalid = 0;
rsa->isprivate = 0;
}
// Create a RSA object.
static int rsaCreate(struct s_rsa *rsa) {
rsa->bn = BN_new();
if(rsa->bn != NULL) {
BN_zero(rsa->bn);
rsa->key = EVP_PKEY_new();
if(rsa->key != NULL) {
rsa->md = EVP_MD_CTX_create();
if(rsa->md != NULL) {
rsaReset(rsa);
return 1;
}
EVP_PKEY_free(rsa->key);
}
BN_free(rsa->bn);
}
return 0;
}
// Destroy a RSA object.
static void rsaDestroy(struct s_rsa *rsa) {
rsaReset(rsa);
EVP_MD_CTX_destroy(rsa->md);
EVP_PKEY_free(rsa->key);
BN_free(rsa->bn);
}
#endif // F_RSA_C
| 7,099 |
C
|
.c
| 247 | 25.906883 | 139 | 0.613803 |
strfry/peervpn
| 2 | 101 | 0 |
GPL-3.0
|
9/7/2024, 2:34:05 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,933,277 |
ctr.c
|
strfry_peervpn/libp2psec/ctr.c
|
/***************************************************************************
* Copyright (C) 2014 by Tobias Volk *
* [email protected] *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
#ifndef F_CTR_C
#define F_CTR_C
#include "util.c"
// Number of seconds for averaging.
#define ctr_SECS 16
// The sequence number state structure.
struct s_ctr_state {
int total;
int cur;
int last[ctr_SECS + 16];
int lasttime;
int lastpos;
};
// Clear counters.
static void ctrClear(struct s_ctr_state *ctr) {
int i;
ctr->total = 0;
ctr->cur = 0;
for(i=0; i<ctr_SECS; i++) {
ctr->last[i] = 0;
}
}
// Initialize sequence number state.
static void ctrInit(struct s_ctr_state *ctr) {
ctrClear(ctr);
ctr->lasttime = utilGetClock();
ctr->lastpos = 0;
}
// Increment counter.
static void ctrIncr(struct s_ctr_state *ctr, const int inc) {
int diff;
int lasttime = ctr->lasttime;
int tnow = utilGetClock();
diff = (tnow - lasttime);
if(diff > ctr_SECS) {
ctrClear(ctr);
}
else {
while(diff > 1) {
ctr->last[ctr->lastpos] = 0;
ctr->lastpos = ((ctr->lastpos + 1) % ctr_SECS);
diff--;
}
if(diff > 0) {
ctr->last[ctr->lastpos] = ctr->cur;
ctr->lastpos = ((ctr->lastpos + 1) % ctr_SECS);
ctr->cur = 0;
diff--;
}
}
ctr->cur = (ctr->cur + inc);
ctr->total = (ctr->total + inc);
ctr->lasttime = tnow;
}
static int ctrAvg(struct s_ctr_state *ctr) {
int i = 0;
int sum = 0;
while(i < ctr_SECS) {
sum = sum + ctr->last[i];
i++;
}
return(sum / ctr_SECS);
}
#endif // F_CTR_C
| 2,652 |
C
|
.c
| 81 | 30.45679 | 77 | 0.52295 |
strfry/peervpn
| 2 | 101 | 0 |
GPL-3.0
|
9/7/2024, 2:34:05 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,933,280 |
util.c
|
strfry_peervpn/libp2psec/util.c
|
/***************************************************************************
* Copyright (C) 2012 by Tobias Volk *
* [email protected] *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
#ifndef F_UTIL_C
#define F_UTIL_C
#include <string.h>
#include <stdint.h>
#include <time.h>
// Convert a 4 bit number to a hexchar.
static char util4BitToHexchar(const int n) {
if(n < 10) return ('0' + n);
if(n < 16) return ('A' - 10 + n);
return ('\0');
}
// Convert a byte array to a hexstring.
static int utilByteArrayToHexstring(char *str, const int strlen, const unsigned char *arr, const int arrlen) {
int l, r, p, i;
if(!((arrlen * 2) < strlen)) return 0;
p = 0;
for(i=0; i<arrlen; i++) {
l = ((arr[i] & 0xF0) >> 4);
r = (arr[i] & 0x0F);
str[p++] = util4BitToHexchar(l);
str[p++] = util4BitToHexchar(r);
}
str[p++] = '\0';
return 1;
}
// Convert a string to uppercase and change all non-alphanumeric characters to '_'.
static void utilStringFilter(char *strout, const char *strin, const int strlen) {
int i, c;
i = 0;
while(i < strlen) {
c = strin[i];
if(c >= 'a' && c <= 'z') {
strout[i] = (c - 'a' + 'A');
}
else if((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z')) {
strout[i] = c;
}
else if(c == '\0') {
strout[i] = '\0';
break;
}
else {
strout[i] = '_';
}
i++;
}
}
// Determine endianness
static int utilIsLittleEndian() {
const unsigned char s[4] = { 1, 0, 0, 0 };
const int32_t *n = (int32_t *)&s;
return (*n == 1);
}
// Read 16 bit integer
static int16_t utilReadInt16(const unsigned char *buf) {
int16_t i;
if(utilIsLittleEndian()) {
((unsigned char *)&i)[0] = buf[1];
((unsigned char *)&i)[1] = buf[0];
return i;
}
else {
memcpy((unsigned char *)&i, buf, 2);
return i;
}
}
// Write 16 bit integer
static void utilWriteInt16(unsigned char *buf, int16_t i) {
if(utilIsLittleEndian()) {
buf[0] = ((unsigned char *)&i)[1];
buf[1] = ((unsigned char *)&i)[0];
}
else {
memcpy(buf, (unsigned char *)&i, 2);
}
}
// Read 32 bit integer
static int32_t utilReadInt32(const unsigned char *buf) {
int32_t i;
if(utilIsLittleEndian()) {
((unsigned char *)&i)[0] = buf[3];
((unsigned char *)&i)[1] = buf[2];
((unsigned char *)&i)[2] = buf[1];
((unsigned char *)&i)[3] = buf[0];
return i;
}
else {
memcpy((unsigned char *)&i, buf, 4);
return i;
}
}
// Write 32 bit integer
static void utilWriteInt32(unsigned char *buf, int32_t i) {
if(utilIsLittleEndian()) {
buf[0] = ((unsigned char *)&i)[3];
buf[1] = ((unsigned char *)&i)[2];
buf[2] = ((unsigned char *)&i)[1];
buf[3] = ((unsigned char *)&i)[0];
}
else {
memcpy(buf, (unsigned char *)&i, 4);
}
}
// Read 64 bit integer
static int64_t utilReadInt64(const unsigned char *buf) {
int64_t i;
if(utilIsLittleEndian()) {
((unsigned char *)&i)[0] = buf[7];
((unsigned char *)&i)[1] = buf[6];
((unsigned char *)&i)[2] = buf[5];
((unsigned char *)&i)[3] = buf[4];
((unsigned char *)&i)[4] = buf[3];
((unsigned char *)&i)[5] = buf[2];
((unsigned char *)&i)[6] = buf[1];
((unsigned char *)&i)[7] = buf[0];
return i;
}
else {
memcpy((unsigned char *)&i, buf, 8);
return i;
}
}
// Write 64 bit integer
static void utilWriteInt64(unsigned char *buf, int64_t i) {
if(utilIsLittleEndian()) {
buf[0] = ((unsigned char *)&i)[7];
buf[1] = ((unsigned char *)&i)[6];
buf[2] = ((unsigned char *)&i)[5];
buf[3] = ((unsigned char *)&i)[4];
buf[4] = ((unsigned char *)&i)[3];
buf[5] = ((unsigned char *)&i)[2];
buf[6] = ((unsigned char *)&i)[1];
buf[7] = ((unsigned char *)&i)[0];
}
else {
memcpy(buf, (unsigned char *)&i, 8);
}
}
// Get clock value in seconds
static int utilGetClock() {
return time(NULL);
}
#endif // F_UTIL_C
| 4,863 |
C
|
.c
| 160 | 28.06875 | 110 | 0.542674 |
strfry/peervpn
| 2 | 101 | 0 |
GPL-3.0
|
9/7/2024, 2:34:05 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,933,285 |
map.c
|
strfry_peervpn/libp2psec/map.c
|
/***************************************************************************
* Copyright (C) 2015 by Tobias Volk *
* [email protected] *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
#ifndef F_MAP_C
#define F_MAP_C
#include "idsp.c"
#include <stdlib.h>
#include <string.h>
// The map struct.
struct s_map {
struct s_idsp idsp;
unsigned char *key;
unsigned char *value;
int *left;
int *right;
int maxnode;
int rootid;
int key_size;
int value_size;
int replace_old;
};
// Enables replacing of old entries if map is full.
static void mapEnableReplaceOld(struct s_map *map) {
map->replace_old = 1;
}
// Disables replacing of old entries if map is full.
static void mapDisableReplaceOld(struct s_map *map) {
map->replace_old = 0;
}
// Return the size of a stored key.
static int mapGetKeySize(struct s_map *map) {
return map->key_size;
}
// Return the size of a stored value.
static int mapGetValueSize(struct s_map *map) {
return map->value_size;
}
// Return 1 if ID is valid.
static int mapIsValidID(struct s_map *map, const int id) {
return idspIsValid(&map->idsp, id);
}
// Return a pointer to key[id].
static void *mapGetKeyByID(struct s_map *map, const int id) {
if((!(id < 0)) && (map != NULL)) {
return &map->key[id * mapGetKeySize(map)];
}
else {
return NULL;
}
}
// Compare stored prefix to an external prefix.
static int mapComparePrefixExt(struct s_map *map, const int id, const void *prefix, const int prefixlen) {
void *skey = mapGetKeyByID(map, id);
return memcmp(skey, prefix, prefixlen);
}
// Compare stored key to an external key.
static int mapCompareKeysExt(struct s_map *map, const int id, const void *key) {
return mapComparePrefixExt(map, id, key, mapGetKeySize(map));
}
// Move the node with the specified key prefix to the root. Return 1 if the key has been found, or 0 if not.
static int mapSplayPrefix(struct s_map *map, const void *prefix, const int prefixlen) {
int ret = 0;
int cur_nodeid = map->rootid;
int maxnode = map->maxnode;
int l = maxnode;
int r = maxnode;
int cur_cmp;
int y;
if(cur_nodeid < 0) return ret;
map->left[maxnode] = -1;
map->right[maxnode] = -1;
for(;;) {
cur_cmp = mapComparePrefixExt(map, cur_nodeid, prefix, prefixlen);
if(cur_cmp > 0) {
y = map->left[cur_nodeid];
if(y < 0) break;
if(mapComparePrefixExt(map, y, prefix, prefixlen) > 0) {
map->left[cur_nodeid] = map->right[y];
map->right[y] = cur_nodeid;
cur_nodeid = y;
if(map->left[cur_nodeid] < 0) break;
}
map->left[r] = cur_nodeid;
r = cur_nodeid;
cur_nodeid = map->left[cur_nodeid];
}
else if(cur_cmp < 0) {
y = map->right[cur_nodeid];
if(y < 0) break;
if(mapComparePrefixExt(map, y, prefix, prefixlen) < 0) {
map->right[cur_nodeid] = map->left[y];
map->left[y] = cur_nodeid;
cur_nodeid = y;
if(map->right[cur_nodeid] < 0) break;
}
map->right[l] = cur_nodeid;
l = cur_nodeid;
cur_nodeid = map->right[cur_nodeid];
}
else {
ret = 1;
break;
}
}
map->right[l] = map->left[cur_nodeid];
map->left[r] = map->right[cur_nodeid];
map->left[cur_nodeid] = map->right[maxnode];
map->right[cur_nodeid] = map->left[maxnode];
map->rootid = cur_nodeid;
return ret;
}
// Move the node with the specified key to the root. Return 1 if the key has been found, or 0 if not.
static int mapSplayKey(struct s_map *map, const void *key) {
return mapSplayPrefix(map, key, mapGetKeySize(map));
}
// Initialize the map. This removes all key/value pairs.
static void mapInit(struct s_map *map) {
idspReset(&map->idsp);
map->maxnode = 0;
map->rootid = -1;
}
// Return the map size.
static int mapGetMapSize(struct s_map *map) {
return idspSize(&map->idsp);
}
// Return the current amount of stored keys.
static int mapGetKeyCount(struct s_map *map) {
return idspUsedCount(&map->idsp);
}
// Return the next ID of a valid key.
static int mapGetNextKeyID(struct s_map *map) {
return idspNext(&map->idsp);
}
// Return the next ID of a valid key, starting from specified ID.
static int mapGetNextKeyIDN(struct s_map *map, const int start) {
return idspNextN(&map->idsp, start);
}
// Get the ID of a key that starts with the specified prefix. Returns the ID or -1 if no key is found.
static int mapGetPrefixID(struct s_map *map, const void *prefix, const int prefixlen) {
if(mapSplayPrefix(map, prefix, prefixlen)) {
return map->rootid;
}
else {
return -1;
}
}
// Get the ID of specified key. Returns the ID or -1 if the key is not found.
static int mapGetKeyID(struct s_map *map, const void *key) {
return mapGetPrefixID(map, key, mapGetKeySize(map));
}
// Get the ID of an "old" key (located near the bottom of the tree).
static int mapGetOldKeyID(struct s_map *map) {
int l;
int r;
int cur_nodeid = map->rootid;
if(!(cur_nodeid < 0)) {
if(!((l = (map->left[cur_nodeid])) < 0)) {
cur_nodeid = l;
while(!(((r = (map->right[cur_nodeid])) < 0) && ((l = (map->left[cur_nodeid])) < 0))) {
if(r < 0) {
cur_nodeid = l;
}
else {
cur_nodeid = r;
}
}
return cur_nodeid;
}
else {
if(!((r = (map->right[cur_nodeid])) < 0)) {
cur_nodeid = r;
while(!(((l = (map->left[cur_nodeid])) < 0) && ((r = (map->right[cur_nodeid])) < 0))) {
if(l < 0) {
cur_nodeid = r;
}
else {
cur_nodeid = l;
}
}
return cur_nodeid;
}
else {
return cur_nodeid;
}
}
}
else {
return -1;
}
}
// Return a pointer to value[id].
static void *mapGetValueByID(struct s_map *map, const int id) {
if((!(id < 0)) && (map != NULL)) {
return &map->value[id * mapGetValueSize(map)];
}
else {
return NULL;
}
}
// Set new value[id].
static void mapSetValueByID(struct s_map *map, const int id, const void *value) {
unsigned char *tptr = mapGetValueByID(map, id);
if((!(id < 0)) && (map != NULL)) {
if(value == NULL) {
memset(tptr, 0, mapGetValueSize(map));
}
else {
memcpy(tptr, value, mapGetValueSize(map));
}
}
}
// Remove the specified key/value pair. Returns removed key ID on success or -1 if the operation fails.
static int mapRemoveReturnID(struct s_map *map, const void *key) {
int x = mapSplayKey(map, key);
int rootid = map->rootid;
if(!x) return -1;
idspDelete(&map->idsp, rootid);
if(idspUsedCount(&map->idsp) > 0) {
if(map->left[rootid] < 0) {
map->rootid = map->right[rootid];
}
else {
x = map->right[rootid];
map->rootid = map->left[rootid];
mapSplayKey(map, key);
map->right[map->rootid] = x;
}
}
else {
map->rootid = -1;
}
return rootid;
}
// Remove the specified key/value pair. Returns 1 on success or 0 if the operation fails.
static int mapRemove(struct s_map *map, const void *key) {
if(mapRemoveReturnID(map, key) < 0) {
return 0;
}
else {
return 1;
}
}
// Add the specified key/value pair. Returns added key ID on success or -1 if the operation fails.
static int mapAddReturnID(struct s_map *map, const void *key, const void *value) {
int x;
int rootid;
int nodeid;
// check if map is full
if(!(idspUsedCount(&map->idsp) < idspSize(&map->idsp))) {
if(map->replace_old > 0) {
// replace old entry if map is full
x = mapGetOldKeyID(map);
if(x < 0) {
return -1;
}
else {
if(!(mapRemove(map, mapGetKeyByID(map, x)))) {
return -1;
}
}
}
else {
// return -1 if map is full
return -1;
}
}
// call splay operation
x = mapSplayKey(map, key);
rootid = map->rootid;
// check if the key is already there
if(x) return -1;
// calculate new nodeid
nodeid = idspNew(&map->idsp);
if((nodeid + 1) > map->maxnode) map->maxnode = (nodeid + 1);
// add the new key
if(rootid < 0) {
map->left[nodeid] = -1;
map->right[nodeid] = -1;
}
else {
if(mapCompareKeysExt(map, rootid, key) > 0) {
map->left[nodeid] = map->left[rootid];
map->right[nodeid] = rootid;
map->left[rootid] = -1;
}
else {
map->right[nodeid] = map->right[rootid];
map->left[nodeid] = rootid;
map->right[rootid] = -1;
}
}
// copy key/value to data structure
memcpy(mapGetKeyByID(map, nodeid), key, mapGetKeySize(map));
mapSetValueByID(map, nodeid, value);
// update root ID
map->rootid = nodeid;
return nodeid;
}
// Add the specified key/value pair. Returns 1 on success or 0 if the operation fails.
static int mapAdd(struct s_map *map, const void *key, const void *value) {
if(mapAddReturnID(map, key, value) < 0) {
return 0;
}
else {
return 1;
}
}
// Sets the specified key/value pair. The key will be added if it doesn't exist yet. Returns key ID on success or -1 if the operation fails.
static int mapSetReturnID(struct s_map *map, const void *key, const void *value) {
int ret = mapAddReturnID(map, key, value);
if(ret < 0) {
ret = mapGetKeyID(map, key);
if(ret < 0) {
return -1;
}
else {
mapSetValueByID(map, ret, value);
return ret;
}
}
else {
return ret;
}
}
// Sets the specified key/value pair. The key will be created if it doesn't exist yet. Returns 1 on success or 0 if the operation fails.
static int mapSet(struct s_map *map, const void *key, const void *value) {
if(mapSetReturnID(map, key, value) < 0) {
return 0;
}
else {
return 1;
}
}
// Return a pointer to the value of a key that matches the specified prefix.
static void *mapGetN(struct s_map *map, const void *prefix, const int prefixlen) {
int id;
id = mapGetPrefixID(map, prefix, prefixlen);
if(id < 0) return NULL;
return mapGetValueByID(map, id);
}
// Return a pointer to the value of the specified key.
static void *mapGet(struct s_map *map, const void *key) {
return mapGetN(map, key, mapGetKeySize(map));
}
// Calculate required memory size for map.
static int mapMemSize(const int map_size, const int key_size, const int value_size) {
const int align_boundary = idsp_ALIGN_BOUNDARY;
int memsize;
memsize = 0;
memsize = memsize + ((((sizeof(struct s_map)) + (align_boundary - 1)) / align_boundary) * align_boundary);
memsize = memsize + ((((map_size * key_size) + (align_boundary - 1)) / align_boundary) * align_boundary);
memsize = memsize + ((((map_size * value_size) + (align_boundary - 1)) / align_boundary) * align_boundary);
memsize = memsize + (((((map_size+1) * sizeof(int)) + (align_boundary - 1)) / align_boundary) * align_boundary);
memsize = memsize + (((((map_size+1) * sizeof(int)) + (align_boundary - 1)) / align_boundary) * align_boundary);
memsize = memsize + (((idspMemSize(map_size) + (align_boundary - 1)) / align_boundary) * align_boundary);
return memsize;
}
// Set up map data structure on preallocated memory.
static int mapMemInit(struct s_map *map, const int mem_size, const int map_size, const int key_size, const int value_size) {
const int align_boundary = idsp_ALIGN_BOUNDARY;
const int keymem_offset = ((((sizeof(struct s_map)) + (align_boundary - 1)) / align_boundary) * align_boundary);
const int valuemem_offset = keymem_offset + ((((map_size * key_size) + (align_boundary - 1)) / align_boundary) * align_boundary);
const int leftmem_offset = valuemem_offset + ((((map_size * value_size) + (align_boundary - 1)) / align_boundary) * align_boundary);
const int rightmem_offset = leftmem_offset + (((((map_size+1) * sizeof(int)) + (align_boundary - 1)) / align_boundary) * align_boundary);
const int idsp_offset = rightmem_offset + (((((map_size+1) * sizeof(int)) + (align_boundary - 1)) / align_boundary) * align_boundary);
const int min_mem_size = idsp_offset + (((idspMemSize(map_size) + (align_boundary - 1)) / align_boundary) * align_boundary);
struct s_idsp *idsp_new;
unsigned char *map_mem;
// check parameters
if(!((map_size > 0) && (key_size > 0) && (value_size > 0))) return 0;
// create data structure
map_mem = (unsigned char *)map;
if(min_mem_size == mapMemSize(map_size, key_size, value_size) && mem_size >= min_mem_size) {
map->key_size = key_size;
map->value_size = value_size;
map->key = (unsigned char *)(&map_mem[keymem_offset]);
map->value = (unsigned char *)(&map_mem[valuemem_offset]);
map->left = (int *)(&map_mem[leftmem_offset]);
map->right = (int *)(&map_mem[rightmem_offset]);
idsp_new = (struct s_idsp *)(&map_mem[idsp_offset]);
if(idspMemInit(idsp_new, (min_mem_size - idsp_offset), map_size)) {
map->idsp = *idsp_new;
mapInit(map);
mapDisableReplaceOld(map);
return 1;
}
}
return 0;
}
// Allocate memory for the map.
static int mapCreate(struct s_map *map, const int map_size, const int key_size, const int value_size) {
// check parameters
if(!((map_size > 0) && (key_size > 0) && (value_size > 0))) return 0;
// create map
void *keymem = NULL;
void *valuemem = NULL;
int *leftmem = NULL;
int *rightmem = NULL;
if((keymem = malloc(map_size * key_size)) == NULL) { return 0; }
if((valuemem = malloc(map_size * value_size)) == NULL) { free(keymem); return 0; }
if((leftmem = malloc((map_size+1) * sizeof(int))) == NULL) { free(valuemem); free(keymem); return 0; }
if((rightmem = malloc((map_size+1) * sizeof(int))) == NULL) { free(leftmem); free(valuemem); free(keymem); return 0; }
if(!idspCreate(&map->idsp, map_size)) { free(rightmem); free(leftmem); free(valuemem); free(keymem); return 0; }
map->key_size = key_size;
map->value_size = value_size;
map->key = keymem;
map->value = valuemem;
map->left = leftmem;
map->right = rightmem;
mapInit(map);
mapDisableReplaceOld(map);
return 1;
}
// Free the memory used by the map.
static int mapDestroy(struct s_map *map) {
// destroy map
if(!((map != NULL) && (map->key != NULL) && (map->value != NULL) && (map->left != NULL) && (map->right != NULL))) return 0;
idspDestroy(&map->idsp);
free(map->right);
free(map->left);
free(map->value);
free(map->key);
map->right = NULL;
map->left = NULL;
map->value = NULL;
map->key = NULL;
return 1;
}
#endif // F_MAP_C
| 14,945 |
C
|
.c
| 443 | 31.142212 | 140 | 0.646593 |
strfry/peervpn
| 2 | 101 | 0 |
GPL-3.0
|
9/7/2024, 2:34:05 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
15,933,286 |
seq.c
|
strfry_peervpn/libp2psec/seq.c
|
/***************************************************************************
* Copyright (C) 2012 by Tobias Volk *
* [email protected] *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
#ifndef F_SEQ_C
#define F_SEQ_C
#include <stdint.h>
// Size of sequence number in bytes.
#define seq_SIZE 8
// Window size.
#define seq_WINDOWSIZE 16384
// The sequence number state structure.
struct s_seq_state {
int64_t start;
uint64_t mask;
};
// Get sequence number state.
static int64_t seqGet(struct s_seq_state *state) {
return state->start;
}
// Initialize sequence number state.
static void seqInit(struct s_seq_state *state, const int64_t seq) {
state->start = seq;
state->mask = 0;
}
// Verify sequence number. Returns 1 if accepted, else 0.
static int seqVerify(struct s_seq_state *state, const int64_t seq) {
const uint_least64_t one = 1;
int64_t start = state->start;
int64_t seqdiff = (seq - start);
uint64_t mask = state->mask;
uint64_t vmask;
if((seqdiff > 0) && (seqdiff < seq_WINDOWSIZE)) {
// move the window
if(seqdiff > 64) {
seqdiff = (seqdiff - 64);
start = (start + seqdiff);
if(seqdiff > 64) {
mask = 0;
}
else {
mask = (mask << seqdiff);
}
seqdiff = 64;
}
// check for duplicates
vmask = (one << (64 - seqdiff));
if((vmask & mask) == 0) {
// sequence number is accepted
mask = (mask | vmask);
state->start = start;
state->mask = mask;
return 1;
}
else {
// duplicate sequence number is rejected
return 0;
}
}
else {
// out of window sequence number is rejected
return 0;
}
}
// Returns the amount of received sequence numbers out of the last 64.
static int seqRQ(struct s_seq_state *state) {
const int bitc[256] = {
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8
};
const unsigned char *bytes = (unsigned char *)&state->mask;
int c = 0;
int i;
for(i=0; i<(sizeof(uint64_t)); i++) {
c = c + bitc[bytes[i]];
}
return c;
}
#endif // F_SEQ_C
| 3,859 |
C
|
.c
| 106 | 33.707547 | 77 | 0.502947 |
strfry/peervpn
| 2 | 101 | 0 |
GPL-3.0
|
9/7/2024, 2:34:05 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
16,020,957 |
quantize.c
|
xatgithub_byzanz/gifenc/quantize.c
|
/* simple gif encoder
* Copyright (C) 2005 Benjamin Otte <[email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <gtk/gtk.h>
#include <string.h>
#include "gifenc.h"
/*** GENERAL ***/
void
gifenc_palette_free (GifencPalette *palette)
{
g_return_if_fail (palette != NULL);
if (palette->free)
palette->free (palette->data);
g_free (palette);
}
guint
gifenc_palette_get_alpha_index (const GifencPalette *palette)
{
g_return_val_if_fail (palette != NULL, 0);
g_return_val_if_fail (palette->alpha, 0);
return palette->num_colors;
}
guint
gifenc_palette_get_num_colors (const GifencPalette *palette)
{
g_return_val_if_fail (palette != NULL, 0);
return palette->num_colors + (palette->alpha ? 1 : 0);
}
guint
gifenc_palette_get_color (const GifencPalette *palette, guint id)
{
g_return_val_if_fail (palette != NULL, 0);
g_return_val_if_fail (id < palette->num_colors, 0);
return palette->colors[id];
}
/*** SIMPLE ***/
static guint
gifenc_palette_simple_lookup (gpointer data, guint32 color, guint32 *resulting_color)
{
color &= 0xC0C0C0;
*resulting_color = color + 0x202020;
return ((color >> 18) & 0x30) |
((color >> 12) & 0xC) |
((color >> 6) & 0x3);
}
GifencPalette *
gifenc_palette_get_simple (gboolean alpha)
{
GifencPalette *palette;
guint r, g, b, i = 0;
palette = g_new (GifencPalette, 1);
palette->alpha = alpha;
palette->num_colors = 64;
palette->colors = g_new (guint, palette->num_colors);
for (r = 0; r < 4; r++) {
for (g = 0; g < 4; g++) {
for (b = 0; b < 4; b++) {
palette->colors[i++] = (r << 22) + (g << 14) + (b << 6) + 0x202020;
}
}
}
palette->data = GINT_TO_POINTER (alpha ? 1 : 0);
palette->lookup = gifenc_palette_simple_lookup;
palette->free = NULL;
return palette;
}
/*** OCTREE QUANTIZATION ***/
/* maximum number of leaves before starting color reduction */
#define MAX_LEAVES (12000)
/* maximum number of leaves before stopping a running color reduction */
#define STOP_LEAVES (MAX_LEAVES >> 2)
typedef struct _GifencOctree GifencOctree;
struct _GifencOctree {
GifencOctree * children[8]; /* children nodes or NULL */
guint level; /* how deep in tree are we? */
guint red; /* sum of all red pixels */
guint green; /* sum of green pixels */
guint blue; /* sum of blue pixels */
guint count; /* amount of pixels at this node */
guint32 color; /* representations (depending on value):
-1: random non-leaf node
-2: root node
0x1000000: leaf node with undefined color
0-0xFFFFFF: leaf node with defined color */
guint id; /* color index */
};
typedef struct {
GifencOctree * tree;
GSList * non_leaves;
guint num_leaves;
} OctreeInfo;
#define OCTREE_IS_LEAF(tree) ((tree)->color <= 0x1000000)
static GifencOctree *
gifenc_octree_new (void)
{
GifencOctree *ret = g_new0 (GifencOctree, 1);
ret->color = (guint) -1;
return ret;
}
static void
gifenc_octree_free (gpointer data)
{
GifencOctree *tree = data;
guint i;
for (i = 0; i < 8; i++) {
if (tree->children[i])
gifenc_octree_free (tree->children[i]);
}
g_free (tree);
}
#if 0
#define PRINT_NON_LEAVES 1
static void
gifenc_octree_print (GifencOctree *tree, guint flags)
{
#define FLAG_SET(flag) (flags & (flag))
if (OCTREE_IS_LEAF (tree)) {
g_print ("%*s %6d %2X-%2X-%2X\n", tree->level * 2, "", tree->count,
tree->red / tree->count, tree->green / tree->count, tree->blue / tree->count);
} else {
guint i;
if (FLAG_SET(PRINT_NON_LEAVES))
g_print ("%*s %6d\n", tree->level * 2, "", tree->count);
g_assert (tree->red == 0);
g_assert (tree->green == 0);
g_assert (tree->blue == 0);
for (i = 0; i < 8; i++) {
if (tree->children[i])
gifenc_octree_print (tree->children[i], flags);
}
}
#undef FLAG_SET
}
#endif
static guint
color_to_index (guint color, guint level)
{
guint ret;
g_assert (level < 8);
color >>= (7 - level);
ret = (color & 0x10000) ? 4 : 0;
if (color & 0x100)
ret += 2;
if (color & 0x1)
ret ++;
return ret;
}
static void
gifenc_octree_add_one (GifencOctree *tree, guint32 color, guint count)
{
tree->red += ((color >> 16) & 0xFF) * count;
tree->green += ((color >> 8) & 0xFF) * count;
tree->blue += (color & 0xFF) * count;
}
static void
gifenc_octree_add_color (OctreeInfo *info, guint32 color, guint count)
{
guint i;
GifencOctree *tree = info->tree;
color &= 0xFFFFFF;
for (;;) {
tree->count += count;
if (tree->level == 8 || OCTREE_IS_LEAF (tree)) {
if (tree->color < 0x1000000 && tree->color != color) {
GifencOctree *new = gifenc_octree_new ();
new->level = tree->level + 1;
new->count = tree->count - count;
new->red = tree->red; tree->red = 0;
new->green = tree->green; tree->green = 0;
new->blue = tree->blue; tree->blue = 0;
new->color = tree->color; tree->color = (guint) -1;
i = color_to_index (new->color, tree->level);
tree->children[i] = new;
info->non_leaves = g_slist_prepend (info->non_leaves, tree);
} else {
gifenc_octree_add_one (tree, color, count);
return;
}
}
i = color_to_index (color, tree->level);
if (tree->children[i]) {
tree = tree->children[i];
} else {
GifencOctree *new = gifenc_octree_new ();
new->level = tree->level + 1;
gifenc_octree_add_one (new, color, count);
new->count = count;
new->color = color;
tree->children[i] = new;
info->num_leaves++;
return;
}
}
}
static int
octree_compare_count (gconstpointer a, gconstpointer b)
{
return ((const GifencOctree *) a)->count - ((const GifencOctree *) b)->count;
}
static void
gifenc_octree_reduce_one (OctreeInfo *info, GifencOctree *tree)
{
guint i;
g_assert (!OCTREE_IS_LEAF (tree));
for (i = 0; i < 8; i++) {
if (!tree->children[i])
continue;
g_assert (OCTREE_IS_LEAF (tree->children[i]));
tree->red += tree->children[i]->red;
tree->green += tree->children[i]->green;
tree->blue += tree->children[i]->blue;
gifenc_octree_free (tree->children[i]);
tree->children[i] = NULL;
info->num_leaves--;
}
tree->color = 0x1000000;
info->num_leaves++;
info->non_leaves = g_slist_remove (info->non_leaves, tree);
}
static void
gifenc_octree_reduce_colors (OctreeInfo *info, guint stop)
{
info->non_leaves = g_slist_sort (info->non_leaves, octree_compare_count);
//g_print ("reducing %u leaves (%u non-leaves)\n", info->num_leaves,
// g_slist_length (info->non_leaves));
while (info->num_leaves > stop) {
gifenc_octree_reduce_one (info, info->non_leaves->data);
}
//g_print (" ==> to %u leaves\n", info->num_leaves);
}
static guint
gifenc_octree_finalize (GifencOctree *tree, guint start_id, guint *colors)
{
if (OCTREE_IS_LEAF (tree)) {
if (tree->color > 0xFFFFFF)
tree->color =
((tree->red / tree->count) << 16) |
((tree->green / tree->count) << 8) |
(tree->blue / tree->count);
tree->id = start_id;
colors[start_id] = tree->color;
return tree->id + 1;
} else {
guint i;
for (i = 0; i < 8; i++) {
if (tree->children[i])
start_id = gifenc_octree_finalize (tree->children[i], start_id, colors);
}
return start_id;
}
g_assert_not_reached ();
return 0;
}
static guint
gifenc_octree_lookup (gpointer data, guint32 color, guint32 *looked_up_color)
{
GifencOctree *tree = data;
guint idx;
if (OCTREE_IS_LEAF (tree)) {
*looked_up_color = tree->color;
return tree->id;
}
idx = color_to_index (color, tree->level);
if (tree->children[idx] == NULL) {
static const guint order[8][7] = {
{ 2, 1, 4, 3, 6, 5, 7 },
{ 3, 0, 5, 2, 7, 4, 6 },
{ 0, 3, 6, 1, 4, 7, 5 },
{ 1, 2, 7, 6, 5, 0, 4 },
{ 6, 5, 0, 7, 2, 1, 3 },
{ 7, 4, 1, 6, 3, 0, 2 },
{ 4, 7, 2, 5, 0, 3, 1 },
{ 5, 6, 3, 4, 1, 2, 0 }
};
guint i, tmp;
for (i = 0; i < 7; i++) {
tmp = order[idx][i];
if (!tree->children[tmp])
continue;
/* make selection smarter, like using closest match */
return gifenc_octree_lookup (
tree->children[tmp],
color, looked_up_color);
}
g_assert_not_reached ();
}
return gifenc_octree_lookup (
tree->children[idx],
color, looked_up_color);
}
GifencPalette *
gifenc_quantize_image (const guint8 *data, guint width, guint height,
guint rowstride, gboolean alpha, guint max_colors)
{
guint x, y;
const guint32 *row;
OctreeInfo info = { NULL, NULL, 0 };
GifencPalette *palette;
g_return_val_if_fail (width * height <= (G_MAXUINT >> 8), NULL);
info.tree = gifenc_octree_new ();
info.tree->color = (guint) -2; /* special node */
if (TRUE) {
guint r, g, b;
static const guint8 colors[] = { 0, 85, 170, 255 };
for (r = 0; r < 4; r++) {
for (g = 0; g < 4; g++) {
for (b = 0; b < 4; b++) {
gifenc_octree_add_color (&info,
(colors[r] << 16) + (colors[g] << 8) + colors[b], 1);
}
}
}
}
for (y = 0; y < height; y++) {
row = (const guint32 *) data;
for (x = 0; x < width; x++) {
gifenc_octree_add_color (&info, row[x] & 0xFFFFFF, 1);
}
//if (info.num_leaves > MAX_LEAVES)
// gifenc_octree_reduce_colors (&info, STOP_LEAVES);
data += rowstride;
}
//gifenc_octree_print (info.tree, 1);
gifenc_octree_reduce_colors (&info, max_colors - (alpha ? 1 : 0));
//gifenc_octree_print (info.tree, 1);
//g_print ("total: %u colors (%u non-leaves)\n", info.num_leaves,
// g_slist_length (info.non_leaves));
palette = g_new (GifencPalette, 1);
palette->alpha = alpha;
palette->colors = g_new (guint, info.num_leaves);
palette->num_colors = info.num_leaves;
palette->data = info.tree;
palette->lookup = gifenc_octree_lookup;
palette->free = gifenc_octree_free;
gifenc_octree_finalize (info.tree, 0, palette->colors);
g_slist_free (info.non_leaves);
return (GifencPalette *) palette;
}
| 10,703 |
C
|
.c
| 356 | 26.691011 | 85 | 0.631681 |
xatgithub/byzanz
| 2 | 18 | 0 |
GPL-3.0
|
9/7/2024, 2:35:06 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
16,020,958 |
gifenc.h
|
xatgithub_byzanz/gifenc/gifenc.h
|
/* simple gif encoder
* Copyright (C) 2005 Benjamin Otte <[email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include <glib.h>
#include <gtk/gtk.h>
#ifndef __HAVE_GIFENC_H__
#define __HAVE_GIFENC_H__
typedef struct _GifencPalette GifencPalette;
typedef struct _GifencColor GifencColor;
typedef struct _Gifenc Gifenc;
typedef gboolean (* GifencWriteFunc) (gpointer closure, const guchar *data, gsize len, GError **error);
typedef enum {
GIFENC_STATE_NEW = 0,
GIFENC_STATE_INITIALIZED,
GIFENC_STATE_CLOSED,
} GifencState;
struct _GifencPalette {
gboolean alpha;
guint32 * colors;
guint num_colors;
guint byte_order;
gpointer data;
guint (* lookup) (gpointer data,
guint32 color,
guint32 * resulting_color);
void (* free) (gpointer data);
};
struct _Gifenc {
/* error checking */
GifencState state;
/* output */
GifencWriteFunc write_func;
gpointer write_data;
GDestroyNotify write_destroy;
GByteArray * buffer;
guint bits;
guint n_bits;
/* image */
guint width;
guint height;
guint byte_order;
GifencPalette * palette;
};
Gifenc * gifenc_new (guint width,
guint height,
GifencWriteFunc write_func,
gpointer write_data,
GDestroyNotify write_destroy);
gboolean gifenc_free (Gifenc * enc);
gboolean gifenc_initialize (Gifenc * enc,
GifencPalette * palette,
gboolean loop,
GError ** error);
gboolean gifenc_add_image (Gifenc * enc,
guint x,
guint y,
guint width,
guint height,
guint display_millis,
guint8 * data,
guint rowstride,
GError ** error);
gboolean gifenc_close (Gifenc * gifenc,
GError ** error);
guint gifenc_get_width (Gifenc * gifenc);
guint gifenc_get_height (Gifenc * gifenc);
void gifenc_dither_rgb (guint8 * target,
guint target_rowstride,
const GifencPalette * palette,
const guint8 * data,
guint width,
guint height,
guint rowstride);
gboolean gifenc_dither_rgb_with_full_image
(guint8 * target,
guint target_rowstride,
guint8 * full,
guint full_rowstride,
const GifencPalette * palette,
const guint8 * data,
guint width,
guint height,
guint rowstride,
cairo_rectangle_int_t * rect_out);
/* from quantize.c */
void gifenc_palette_free (GifencPalette * palette);
GifencPalette * gifenc_palette_get_simple (gboolean alpha);
GifencPalette * gifenc_quantize_image (const guint8 * data,
guint width,
guint height,
guint rowstride,
gboolean alpha,
guint max_colors);
guint gifenc_palette_get_alpha_index
(const GifencPalette * palette);
guint gifenc_palette_get_num_colors
(const GifencPalette * palette);
guint32 gifenc_palette_get_color(const GifencPalette * palette,
guint id);
#endif /* __HAVE_GIFENC_H__ */
| 4,196 |
C
|
.c
| 115 | 30.078261 | 103 | 0.603257 |
xatgithub/byzanz
| 2 | 18 | 0 |
GPL-3.0
|
9/7/2024, 2:35:06 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
16,020,968 |
byzanzencoder.c
|
xatgithub_byzanz/src/byzanzencoder.c
|
/* desktop session recorder
* Copyright (C) 2009 Benjamin Otte <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "byzanzencoder.h"
#include <glib/gi18n-lib.h>
#include "byzanzserialize.h"
typedef struct _ByzanzEncoderJob ByzanzEncoderJob;
struct _ByzanzEncoderJob {
GTimeVal tv; /* time this job was enqueued */
cairo_surface_t * surface; /* image to process */
cairo_region_t * region; /* relevant region of image */
};
static void
byzanz_encoder_job_free (ByzanzEncoderJob *job)
{
if (job->surface)
cairo_surface_destroy (job->surface);
if (job->region)
cairo_region_destroy (job->region);
g_slice_free (ByzanzEncoderJob, job);
}
static gboolean
byzanz_encoder_finished (gpointer data)
{
ByzanzEncoder *encoder = data;
ByzanzEncoderJob *job;
encoder->error = g_thread_join (encoder->thread);
encoder->thread = NULL;
while ((job = g_async_queue_try_pop (encoder->jobs)))
byzanz_encoder_job_free (job);
g_object_freeze_notify (G_OBJECT (encoder));
g_object_notify (G_OBJECT (encoder), "running");
if (encoder->error)
g_object_notify (G_OBJECT (encoder), "error");
g_object_thaw_notify (G_OBJECT (encoder));
g_object_unref (encoder);
return FALSE;
}
/*** INSIDE THREAD ***/
static gboolean
byzanz_encoder_run (ByzanzEncoder * encoder,
GInputStream * input,
GOutputStream * output,
gboolean record_audio,
GCancellable * cancellable,
GError ** error)
{
ByzanzEncoderClass *klass = BYZANZ_ENCODER_GET_CLASS (encoder);
guint width, height;
cairo_surface_t *surface;
cairo_region_t *region;
guint64 msecs;
gboolean success;
if (record_audio) {
g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
_("This format does not support recording audio."));
return FALSE;
}
if (!byzanz_deserialize_header (input, &width, &height, cancellable, error) ||
!klass->setup (encoder, output, width, height, cancellable, error))
return FALSE;
for (;;) {
if (!byzanz_deserialize (input , &msecs, &surface, ®ion, cancellable, error))
return FALSE;
/* quit */
if (surface == NULL) {
return klass->close (encoder, output, msecs, cancellable, error) &&
g_output_stream_close (output, cancellable, error);
}
/* decode */
success = klass->process (encoder, output, msecs, surface, region, cancellable, error);
cairo_surface_destroy (surface);
cairo_region_destroy (region);
if (!success)
return FALSE;
}
}
static gpointer
byzanz_encoder_thread (gpointer enc)
{
ByzanzEncoder *encoder = BYZANZ_ENCODER (enc);
ByzanzEncoderClass *klass = BYZANZ_ENCODER_GET_CLASS (encoder);
GError *error = NULL;
klass->run (encoder, encoder->input_stream, encoder->output_stream,
encoder->record_audio, encoder->cancellable, &error);
g_idle_add_full (G_PRIORITY_DEFAULT, byzanz_encoder_finished, enc, NULL);
return error;
}
/*** OUTSIDE THREAD ***/
enum {
PROP_0,
PROP_INPUT,
PROP_OUTPUT,
PROP_SOUND,
PROP_CANCELLABLE,
PROP_ERROR,
PROP_RUNNING
};
static void
byzanz_encoder_base_init (gpointer klass)
{
ByzanzEncoderClass *encoder_class = klass;
encoder_class->filter = NULL;
}
static void
byzanz_encoder_base_finalize (gpointer klass)
{
ByzanzEncoderClass *encoder_class = klass;
if (encoder_class->filter)
g_object_unref (encoder_class->filter);
}
/* cannot use this here, the file filter requires base_init and base_finalize
* G_DEFINE_ABSTRACT_TYPE (ByzanzEncoder, byzanz_encoder, G_TYPE_OBJECT)
*/
static void byzanz_encoder_init (GTypeInstance *instance, gpointer klass);
static void byzanz_encoder_class_init (ByzanzEncoderClass *klass);
static gpointer byzanz_encoder_parent_class = NULL;
static void byzanz_encoder_class_intern_init (gpointer klass, gpointer data)
{
byzanz_encoder_parent_class = g_type_class_peek_parent (klass);
byzanz_encoder_class_init ((ByzanzEncoderClass*) klass);
}
GType
byzanz_encoder_get_type (void)
{
static volatile gsize g_define_type_id__volatile = 0;
if (g_once_init_enter (&g_define_type_id__volatile)) {
GTypeInfo info = {
sizeof (ByzanzEncoderClass),
byzanz_encoder_base_init,
byzanz_encoder_base_finalize,
byzanz_encoder_class_intern_init,
NULL,
NULL,
sizeof (ByzanzEncoder),
0,
byzanz_encoder_init,
NULL
};
GType g_define_type_id;
g_define_type_id = g_type_register_static (G_TYPE_OBJECT, g_intern_static_string ("ByzanzEncoder"),
&info, G_TYPE_FLAG_ABSTRACT);
g_once_init_leave (&g_define_type_id__volatile, g_define_type_id);
}
return g_define_type_id__volatile;
}
static void
byzanz_encoder_get_property (GObject *object, guint param_id, GValue *value,
GParamSpec * pspec)
{
ByzanzEncoder *encoder = BYZANZ_ENCODER (object);
switch (param_id) {
case PROP_INPUT:
g_value_set_object (value, encoder->input_stream);
break;
case PROP_OUTPUT:
g_value_set_object (value, encoder->output_stream);
break;
case PROP_SOUND:
g_value_set_boolean (value, encoder->record_audio);
break;
case PROP_CANCELLABLE:
g_value_set_object (value, encoder->cancellable);
break;
case PROP_ERROR:
g_value_set_pointer (value, encoder->error);
break;
case PROP_RUNNING:
g_value_set_boolean (value, encoder->thread != NULL);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
break;
}
}
static void
byzanz_encoder_set_property (GObject *object, guint param_id, const GValue *value,
GParamSpec * pspec)
{
ByzanzEncoder *encoder = BYZANZ_ENCODER (object);
switch (param_id) {
case PROP_INPUT:
encoder->input_stream = g_value_dup_object (value);
g_assert (encoder->input_stream != NULL);
break;
case PROP_OUTPUT:
encoder->output_stream = g_value_dup_object (value);
g_assert (encoder->output_stream != NULL);
break;
case PROP_SOUND:
encoder->record_audio = g_value_get_boolean (value);
break;
case PROP_CANCELLABLE:
encoder->cancellable = g_value_dup_object (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
break;
}
}
static void
byzanz_encoder_finalize (GObject *object)
{
ByzanzEncoder *encoder = BYZANZ_ENCODER (object);
g_assert (encoder->thread == NULL);
g_object_unref (encoder->input_stream);
g_object_unref (encoder->output_stream);
if (encoder->cancellable)
g_object_unref (encoder->cancellable);
if (encoder->error)
g_error_free (encoder->error);
g_async_queue_unref (encoder->jobs);
G_OBJECT_CLASS (byzanz_encoder_parent_class)->finalize (object);
}
static void
byzanz_encoder_constructed (GObject *object)
{
ByzanzEncoder *encoder = BYZANZ_ENCODER (object);
encoder->thread = g_thread_new ("encoder", byzanz_encoder_thread, encoder);
if (encoder->thread)
g_object_ref (encoder);
if (G_OBJECT_CLASS (byzanz_encoder_parent_class)->constructed)
G_OBJECT_CLASS (byzanz_encoder_parent_class)->constructed (object);
}
static void
byzanz_encoder_class_init (ByzanzEncoderClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->get_property = byzanz_encoder_get_property;
object_class->set_property = byzanz_encoder_set_property;
object_class->finalize = byzanz_encoder_finalize;
object_class->constructed = byzanz_encoder_constructed;
g_object_class_install_property (object_class, PROP_INPUT,
g_param_spec_object ("input", "input", "stream to read data from",
G_TYPE_INPUT_STREAM, G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
g_object_class_install_property (object_class, PROP_OUTPUT,
g_param_spec_object ("output", "output", "stream to write data to",
G_TYPE_OUTPUT_STREAM, G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
g_object_class_install_property (object_class, PROP_SOUND,
g_param_spec_boolean ("record-audio", "record audio", "TRUE when recording audio",
FALSE, G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
g_object_class_install_property (object_class, PROP_CANCELLABLE,
g_param_spec_object ("cancellable", "cancellable", "cancellable for stopping the thread",
G_TYPE_CANCELLABLE, G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
g_object_class_install_property (object_class, PROP_ERROR,
g_param_spec_pointer ("error", "error", "error that happened on the thread",
G_PARAM_READABLE));
g_object_class_install_property (object_class, PROP_RUNNING,
g_param_spec_boolean ("running", "running", "TRUE while the encoding thread is running",
TRUE, G_PARAM_READABLE));
klass->run = byzanz_encoder_run;
}
static void
byzanz_encoder_init (GTypeInstance *instance, gpointer klass)
{
ByzanzEncoder *encoder = BYZANZ_ENCODER (instance);
encoder->jobs = g_async_queue_new ();
}
ByzanzEncoder *
byzanz_encoder_new (GType encoder_type,
GInputStream * input,
GOutputStream * output,
gboolean record_audio,
GCancellable * cancellable)
{
ByzanzEncoder *encoder;
g_return_val_if_fail (g_type_is_a (encoder_type, BYZANZ_TYPE_ENCODER), NULL);
g_return_val_if_fail (G_IS_INPUT_STREAM (input), NULL);
g_return_val_if_fail (G_IS_OUTPUT_STREAM (output), NULL);
g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL);
encoder = g_object_new (encoder_type, "input", input, "output", output,
"record-audio", record_audio, "cancellable", cancellable, NULL);
return encoder;
}
/*
void
byzanz_encoder_process (ByzanzEncoder * encoder,
cairo_surface_t *surface,
const cairo_region_t *region,
const GTimeVal * total_elapsed)
{
ByzanzEncoderJob *job;
g_return_if_fail (BYZANZ_IS_ENCODER (encoder));
g_return_if_fail (surface != NULL);
g_return_if_fail (region != NULL);
g_return_if_fail (total_elapsed != NULL);
if (encoder->error)
return;
job = g_slice_new (ByzanzEncoderJob);
job->surface = cairo_surface_reference (surface);
job->region = cairo_region_copy (region);
job->tv = *total_elapsed;
g_async_queue_push (encoder->jobs, job);
}
void
byzanz_encoder_close (ByzanzEncoder *encoder,
const GTimeVal * total_elapsed)
{
ByzanzEncoderJob *job;
g_return_if_fail (BYZANZ_IS_ENCODER (encoder));
g_return_if_fail (total_elapsed != NULL);
if (encoder->error)
return;
job = g_slice_new (ByzanzEncoderJob);
job->surface = NULL;
job->region = NULL;
job->tv = *total_elapsed;
g_async_queue_push (encoder->jobs, job);
}
*/
gboolean
byzanz_encoder_is_running (ByzanzEncoder *encoder)
{
g_return_val_if_fail (BYZANZ_IS_ENCODER (encoder), FALSE);
return encoder->thread != NULL;
}
const GError *
byzanz_encoder_get_error (ByzanzEncoder *encoder)
{
g_return_val_if_fail (BYZANZ_IS_ENCODER (encoder), FALSE);
return encoder->error;
}
GtkFileFilter *
byzanz_encoder_type_get_filter (GType encoder_type)
{
ByzanzEncoderClass *klass;
GtkFileFilter *filter;
g_return_val_if_fail (g_type_is_a (encoder_type, BYZANZ_TYPE_ENCODER), NULL);
klass = g_type_class_ref (encoder_type);
filter = klass->filter;
if (filter) {
g_assert (!g_object_is_floating (filter));
g_object_ref (filter);
g_object_set_data (G_OBJECT (filter), "byzanz-encoder-type",
GSIZE_TO_POINTER (encoder_type));
}
g_type_class_unref (klass);
return filter;
}
/* all the encoders */
#include "byzanzencoderbyzanz.h"
#include "byzanzencoderflv.h"
#include "byzanzencodergif.h"
#include "byzanzencoderogv.h"
#include "byzanzencoderwebm.h"
typedef GType (* TypeFunc) (void);
static const TypeFunc functions[] = {
byzanz_encoder_gif_get_type,
byzanz_encoder_webm_get_type,
byzanz_encoder_ogv_get_type,
byzanz_encoder_flv_get_type,
/* debug types */
byzanz_encoder_byzanz_get_type,
};
#define BYZANZ_ENCODER_DEFAULT_TYPE (functions[0] ())
GType
byzanz_encoder_type_iter_init (ByzanzEncoderIter *iter)
{
g_return_val_if_fail (iter != NULL, G_TYPE_NONE);
*iter = GSIZE_TO_POINTER (0);
return functions[0] ();
}
GType
byzanz_encoder_type_iter_next (ByzanzEncoderIter *iter)
{
guint id;
g_return_val_if_fail (iter != NULL, G_TYPE_NONE);
id = GPOINTER_TO_SIZE (*iter);
id++;
if (id >= G_N_ELEMENTS (functions))
return G_TYPE_NONE;
*iter = GSIZE_TO_POINTER (id);
return functions[id] ();
}
GType
byzanz_encoder_get_type_from_filter (GtkFileFilter *filter)
{
GType type;
g_return_val_if_fail (filter == NULL || GTK_IS_FILE_FILTER (filter), BYZANZ_ENCODER_DEFAULT_TYPE);
if (filter == NULL)
return BYZANZ_ENCODER_DEFAULT_TYPE;
type = GPOINTER_TO_SIZE (g_object_get_data (G_OBJECT (filter), "byzanz-encoder-type"));
if (type == 0)
return BYZANZ_ENCODER_DEFAULT_TYPE;
return type;
}
GType
byzanz_encoder_get_type_from_file (GFile *file)
{
ByzanzEncoderIter iter;
GtkFileFilterInfo info;
GType type;
g_return_val_if_fail (G_IS_FILE (file), BYZANZ_ENCODER_DEFAULT_TYPE);
info.contains = 0;
info.filename = g_file_get_path (file);
if (info.filename)
info.contains |= GTK_FILE_FILTER_FILENAME;
info.uri = g_file_get_uri (file);
if (info.uri)
info.contains |= GTK_FILE_FILTER_URI;
/* uh oh */
info.display_name = g_file_get_parse_name (file);
if (info.display_name)
info.contains |= GTK_FILE_FILTER_DISPLAY_NAME;
for (type = byzanz_encoder_type_iter_init (&iter);
type != G_TYPE_NONE;
type = byzanz_encoder_type_iter_next (&iter)) {
GtkFileFilter *filter = byzanz_encoder_type_get_filter (type);
if (filter == NULL)
continue;
if (gtk_file_filter_filter (filter, &info)) {
g_object_unref (filter);
break;
}
g_object_unref (filter);
}
if (type == G_TYPE_NONE)
type = BYZANZ_ENCODER_DEFAULT_TYPE;
g_free ((char *) info.filename);
g_free ((char *) info.uri);
g_free ((char *) info.display_name);
return type;
}
| 14,878 |
C
|
.c
| 441 | 29.886621 | 103 | 0.702024 |
xatgithub/byzanz
| 2 | 18 | 0 |
GPL-3.0
|
9/7/2024, 2:35:06 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
16,020,974 |
byzanzserialize.c
|
xatgithub_byzanz/src/byzanzserialize.c
|
/* desktop session recorder
* Copyright (C) 2009 Benjamin Otte <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "byzanzserialize.h"
#include <string.h>
#include <glib/gi18n.h>
#define IDENTIFICATION "ByzanzRecording"
static guchar
byte_order_to_uchar (void)
{
switch (G_BYTE_ORDER) {
case G_BIG_ENDIAN:
return 'B';
case G_LITTLE_ENDIAN:
return 'L';
default:
g_assert_not_reached ();
return 0;
}
}
gboolean
byzanz_serialize_header (GOutputStream * stream,
guint width,
guint height,
GCancellable * cancellable,
GError ** error)
{
guint32 w, h;
guchar endian;
g_return_val_if_fail (G_IS_OUTPUT_STREAM (stream), FALSE);
g_return_val_if_fail (width <= G_MAXUINT32, FALSE);
g_return_val_if_fail (height <= G_MAXUINT32, FALSE);
w = width;
h = height;
endian = byte_order_to_uchar ();
return g_output_stream_write_all (stream, IDENTIFICATION, strlen (IDENTIFICATION), NULL, cancellable, error) &&
g_output_stream_write_all (stream, &endian, sizeof (guchar), NULL, cancellable, error) &&
g_output_stream_write_all (stream, &w, sizeof (guint32), NULL, cancellable, error) &&
g_output_stream_write_all (stream, &h, sizeof (guint32), NULL, cancellable, error);
}
gboolean
byzanz_deserialize_header (GInputStream * stream,
guint * width,
guint * height,
GCancellable * cancellable,
GError ** error)
{
char result[strlen (IDENTIFICATION) + 1];
guint32 size[2];
guchar endian;
g_return_val_if_fail (G_IS_INPUT_STREAM (stream), FALSE);
g_return_val_if_fail (width != NULL, FALSE);
g_return_val_if_fail (height != NULL, FALSE);
if (!g_input_stream_read_all (stream, result, sizeof (result), NULL, cancellable, error))
return FALSE;
if (strncmp (result, IDENTIFICATION, strlen (IDENTIFICATION)) != 0) {
g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
_("Not a Byzanz recording"));
return FALSE;
}
endian = result[strlen (IDENTIFICATION)];
if (endian != byte_order_to_uchar ()) {
g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
_("Unsupported byte order"));
return FALSE;
}
if (!g_input_stream_read_all (stream, &size, sizeof (size), NULL, cancellable, error))
return FALSE;
*width = size[0];
*height = size[1];
return TRUE;
}
gboolean
byzanz_serialize (GOutputStream * stream,
guint64 msecs,
cairo_surface_t * surface,
const cairo_region_t * region,
GCancellable * cancellable,
GError ** error)
{
guint i, stride;
cairo_rectangle_int_t rect, extents;
guchar *data;
guint32 n;
int y, n_rects;
g_return_val_if_fail (G_IS_OUTPUT_STREAM (stream), FALSE);
g_return_val_if_fail ((surface == NULL) == (region == NULL), FALSE);
g_return_val_if_fail (region == NULL || !cairo_region_is_empty (region), FALSE);
if (!g_output_stream_write_all (stream, &msecs, sizeof (guint64), NULL, cancellable, error))
return FALSE;
if (surface == 0) {
n = 0;
return g_output_stream_write_all (stream, &n, sizeof (guint32), NULL, cancellable, error);
}
n = n_rects = cairo_region_num_rectangles (region);
if (!g_output_stream_write_all (stream, &n, sizeof (guint32), NULL, cancellable, error))
return FALSE;
for (i = 0; i < n; i++) {
gint32 ints[4];
cairo_region_get_rectangle (region, i, &rect);
ints[0] = rect.x, ints[1] = rect.y, ints[2] = rect.width, ints[3] = rect.height;
g_assert (sizeof (ints) == 16);
if (!g_output_stream_write_all (stream, ints, sizeof (ints), NULL, cancellable, error))
return FALSE;
}
stride = cairo_image_surface_get_stride (surface);
cairo_region_get_extents (region, &extents);
for (i = 0; i < n; i++) {
cairo_region_get_rectangle (region, i, &rect);
data = cairo_image_surface_get_data (surface)
+ stride * (rect.y - extents.y)
+ sizeof (guint32) * (rect.x - extents.x);
for (y = 0; y < rect.height; y++) {
if (!g_output_stream_write_all (G_OUTPUT_STREAM (stream), data,
rect.width * sizeof (guint32), NULL, cancellable, error))
return FALSE;
data += stride;
}
}
return TRUE;
}
gboolean
byzanz_deserialize (GInputStream * stream,
guint64 * msecs_out,
cairo_surface_t ** surface_out,
cairo_region_t ** region_out,
GCancellable * cancellable,
GError ** error)
{
guint i, stride;
cairo_rectangle_int_t extents, *rects;
cairo_region_t *region;
cairo_surface_t *surface;
guchar *data;
guint32 n;
int y;
g_return_val_if_fail (G_IS_INPUT_STREAM (stream), FALSE);
g_return_val_if_fail (msecs_out != NULL, FALSE);
g_return_val_if_fail (surface_out != NULL, FALSE);
g_return_val_if_fail (region_out != NULL, FALSE);
if (!g_input_stream_read_all (stream, msecs_out, sizeof (guint64), NULL, cancellable, error) ||
!g_input_stream_read_all (stream, &n, sizeof (guint32), NULL, cancellable, error))
return FALSE;
if (n == 0) {
/* end of stream */
*surface_out = NULL;
*region_out = NULL;
return TRUE;
}
region = cairo_region_create ();
rects = g_new (cairo_rectangle_int_t, n);
surface = NULL;
for (i = 0; i < n; i++) {
gint ints[4];
if (!g_input_stream_read_all (stream, ints, sizeof (ints), NULL, cancellable, error))
goto fail;
rects[i].x = ints[0];
rects[i].y = ints[1];
rects[i].width = ints[2];
rects[i].height = ints[3];
cairo_region_union_rectangle (region, &rects[i]);
}
cairo_region_get_extents (region, &extents);
surface = cairo_image_surface_create (CAIRO_FORMAT_RGB24, extents.width, extents.height);
cairo_surface_set_device_offset (surface, -extents.x, -extents.y);
stride = cairo_image_surface_get_stride (surface);
for (i = 0; i < n; i++) {
data = cairo_image_surface_get_data (surface)
+ stride * (rects[i].y - extents.y)
+ sizeof (guint32) * (rects[i].x - extents.x);
for (y = 0; y < rects[i].height; y++) {
if (!g_input_stream_read_all (stream, data,
rects[i].width * sizeof (guint32), NULL, cancellable, error))
goto fail;
data += stride;
}
}
g_free (rects);
*region_out = region;
*surface_out = surface;
return TRUE;
fail:
if (surface)
cairo_surface_destroy (surface);
cairo_region_destroy (region);
g_free (rects);
return FALSE;
}
| 7,558 |
C
|
.c
| 206 | 31.194175 | 113 | 0.626947 |
xatgithub/byzanz
| 2 | 18 | 0 |
GPL-3.0
|
9/7/2024, 2:35:06 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
16,020,976 |
screenshot-utils.c
|
xatgithub_byzanz/src/screenshot-utils.c
|
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "screenshot-utils.h"
#include <X11/Xatom.h>
#include <gdk/gdkx.h>
static gboolean
get_atom_property (Window xwindow,
Atom atom,
Atom *val)
{
Atom type;
int format;
gulong nitems;
gulong bytes_after;
Atom *a = NULL;
int err, result;
guchar *atom_cast;
*val = 0;
gdk_error_trap_push ();
type = None;
result = XGetWindowProperty (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()),
xwindow,
atom,
0, G_MAXLONG,
False, XA_ATOM, &type, &format, &nitems,
&bytes_after, &atom_cast);
a = (Atom *) atom_cast;
err = gdk_error_trap_pop ();
if (err != Success ||
result != Success)
return FALSE;
if (type != XA_ATOM)
{
XFree (a);
return FALSE;
}
*val = *a;
XFree (a);
return TRUE;
}
static Window
find_toplevel_window (Window xid)
{
Window root, parent, *children;
guint nchildren;
do
{
if (XQueryTree (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), xid, &root,
&parent, &children, &nchildren) == 0)
{
g_warning ("Couldn't find window manager window");
return None;
}
if (root == parent)
return xid;
xid = parent;
}
while (TRUE);
}
static gboolean
screenshot_window_is_desktop (Window xid)
{
Window root_window = GDK_ROOT_WINDOW ();
if (xid == root_window)
return TRUE;
if (gdk_x11_screen_supports_net_wm_hint (gdk_screen_get_default (),
gdk_atom_intern ("_NET_WM_WINDOW_TYPE", FALSE)))
{
gboolean retval;
Atom property;
retval = get_atom_property (xid,
gdk_x11_get_xatom_by_name ("_NET_WM_WINDOW_TYPE"),
&property);
if (retval &&
property == gdk_x11_get_xatom_by_name ("_NET_WM_WINDOW_TYPE_DESKTOP"))
return TRUE;
}
return FALSE;
}
/* We don't actually honor include_decoration here. We need to search
* for WM_STATE;
*/
static Window
screenshot_find_pointer_window (void)
{
Window root_window, root_return, child;
int unused;
guint mask;
root_window = GDK_ROOT_WINDOW ();
XQueryPointer (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), root_window,
&root_return, &child, &unused,
&unused, &unused, &unused, &mask);
return child;
}
#define MAXIMUM_WM_REPARENTING_DEPTH 4
/* adopted from eel code */
static Window
look_for_hint_helper (Window xid,
Atom property,
int depth)
{
Atom actual_type;
int actual_format;
gulong nitems, bytes_after;
gulong *prop;
Window root, parent, *children, window;
guint nchildren, i;
if (XGetWindowProperty (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()),
xid, property, 0, 1,
False, AnyPropertyType, &actual_type,
&actual_format, &nitems, &bytes_after,
(gpointer) &prop) == Success
&& prop != NULL && actual_format == 32 && prop[0] == NormalState)
{
if (prop != NULL)
{
XFree (prop);
}
return xid;
}
if (depth < MAXIMUM_WM_REPARENTING_DEPTH)
{
if (XQueryTree (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), xid, &root,
&parent, &children, &nchildren) != 0)
{
window = None;
for (i = 0; i < nchildren; i++)
{
window = look_for_hint_helper (children[i],
property,
depth + 1);
if (window != None)
break;
}
if (children != NULL)
XFree (children);
if (window)
return window;
}
}
return None;
}
static Window
look_for_hint (Window xid,
Atom property)
{
Window retval;
retval = look_for_hint_helper (xid, property, 0);
return retval;
}
Window
screenshot_find_current_window (gboolean include_decoration)
{
Window current_window;
current_window = screenshot_find_pointer_window ();
if (current_window)
{
if (screenshot_window_is_desktop (current_window))
/* if the current window is the desktop (eg. nautilus), we
* return None, as getting the whole screen makes more sense. */
return None;
/* Once we have a window, we walk the widget tree looking for
* the appropriate window. */
current_window = find_toplevel_window (current_window);
if (! include_decoration)
{
Window new_window;
new_window = look_for_hint (current_window, gdk_x11_get_xatom_by_name ("WM_STATE"));
if (new_window)
current_window = new_window;
}
}
return current_window;
}
| 4,473 |
C
|
.c
| 175 | 20.988571 | 91 | 0.637518 |
xatgithub/byzanz
| 2 | 18 | 0 |
GPL-3.0
|
9/7/2024, 2:35:06 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
16,020,983 |
byzanzselect.c
|
xatgithub_byzanz/src/byzanzselect.c
|
/* desktop session recorder
* Copyright (C) 2005,2009 Benjamin Otte <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "byzanzselect.h"
#include <glib/gi18n.h>
#include "screenshot-utils.h"
static void
rectangle_sanitize (cairo_rectangle_int_t *dest, const cairo_rectangle_int_t *src)
{
*dest = *src;
if (dest->width < 0) {
dest->x += dest->width;
dest->width = -dest->width;
}
if (dest->height < 0) {
dest->y += dest->height;
dest->height = -dest->height;
}
}
typedef struct _ByzanzSelectData ByzanzSelectData;
struct _ByzanzSelectData {
ByzanzSelectFunc func; /* func passed to byzanz_select_method_select() */
gpointer func_data; /* data passed to byzanz_select_method_select() */
/* results */
GdkWindow * result; /* window that was selected */
cairo_rectangle_int_t area; /* the area to select */
/* method data */
GtkWidget * window; /* window we created to do selecting or NULL */
cairo_surface_t * root; /* only used without XComposite, NULL otherwise: the root window */
};
static void
byzanz_select_data_free (gpointer datap)
{
ByzanzSelectData *data = datap;
g_assert (data->window == NULL);
if (data->root)
cairo_surface_destroy (data->root);
if (data->result)
g_object_unref (data->result);
g_slice_free (ByzanzSelectData, data);
}
static gboolean
byzanz_select_really_done (gpointer datap)
{
ByzanzSelectData *data = datap;
data->func (data->result, &data->area, data->func_data);
byzanz_select_data_free (data);
return FALSE;
}
static void
byzanz_select_done (ByzanzSelectData *data, GdkWindow *window)
{
if (data->window) {
gtk_widget_destroy (data->window);
data->window = NULL;
}
if (window) {
/* stupid hack to get around a session recording the selection window */
gdk_display_sync (gdk_window_get_display (window));
data->result = g_object_ref (window);
gdk_threads_add_timeout (1000, byzanz_select_really_done, data);
} else {
byzanz_select_really_done (data);
}
}
/*** SELECT AREA ***/
/* define for SLOW selection mechanism */
#undef TARGET_LINE
static gboolean
expose_cb (GtkWidget *widget, GdkEventExpose *event, gpointer datap)
{
cairo_t *cr;
ByzanzSelectData *data = datap;
#ifdef TARGET_LINE
static double dashes[] = { 1.0, 2.0 };
#endif
cr = gdk_cairo_create (gtk_widget_get_window (widget));
cairo_rectangle (cr, event->area.x, event->area.y, event->area.width, event->area.height);
cairo_clip (cr);
/* clear (or draw) background */
cairo_save (cr);
if (data->root) {
cairo_set_source_surface (cr, data->root, 0, 0);
} else {
cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE);
cairo_set_source_rgba (cr, 0.0, 0.0, 0.0, 0.0);
}
cairo_paint (cr);
cairo_restore (cr);
/* FIXME: make colors use theme */
cairo_set_line_width (cr, 1.0);
#ifdef TARGET_LINE
cairo_set_source_rgba (cr, 1.0, 0.0, 0.0, 1.0);
cairo_set_dash (cr, dashes, G_N_ELEMENTS (dashes), 0.0);
cairo_move_to (cr, data->area.x + data->area.width - 0.5, 0.0);
cairo_line_to (cr, data->area.x + data->area.width - 0.5, event->area.y + event->area.height); /* end of screen really */
cairo_move_to (cr, 0.0, data->area.y + data->area.height - 0.5);
cairo_line_to (cr, event->area.x + event->area.width, data->area.y + data->area.height - 0.5); /* end of screen really */
cairo_stroke (cr);
#endif
if (data->area.x >= 0 && data->area.width != 0 && data->area.height != 0) {
cairo_rectangle_int_t rect = data->area;
rectangle_sanitize (&rect, &data->area);
cairo_set_source_rgba (cr, 0.0, 0.0, 0.5, 0.2);
cairo_set_dash (cr, NULL, 0, 0.0);
gdk_cairo_rectangle (cr, (GdkRectangle *) &rect);
cairo_fill (cr);
cairo_set_source_rgba (cr, 0.0, 0.0, 0.5, 0.5);
cairo_rectangle (cr, rect.x + 0.5, rect.y + 0.5, rect.width - 1, rect.height - 1);
cairo_stroke (cr);
}
if (cairo_status (cr) != CAIRO_STATUS_SUCCESS)
g_printerr ("cairo error: %s\n", cairo_status_to_string (cairo_status (cr)));
cairo_destroy (cr);
return FALSE;
}
static gboolean
button_pressed_cb (GtkWidget *widget, GdkEventButton *event, gpointer datap)
{
ByzanzSelectData *data = datap;
if (event->button != 1) {
byzanz_select_done (data, NULL);
return TRUE;
}
data->area.x = event->x;
data->area.y = event->y;
data->area.width = 1;
data->area.height = 1;
gtk_widget_queue_draw (widget);
return TRUE;
}
static gboolean
button_released_cb (GtkWidget *widget, GdkEventButton *event, gpointer datap)
{
ByzanzSelectData *data = datap;
if (event->button == 1 && data->area.x >= 0) {
data->area.width = event->x - data->area.x;
data->area.height = event->y - data->area.y;
rectangle_sanitize (&data->area, &data->area);
byzanz_select_done (data, gdk_get_default_root_window ());
}
return TRUE;
}
static gboolean
motion_notify_cb (GtkWidget *widget, GdkEventMotion *event, gpointer datap)
{
ByzanzSelectData *data = datap;
#ifdef TARGET_LINE
gtk_widget_queue_draw (widget);
#else
if (data->area.x >= 0) {
cairo_rectangle_int_t rect;
rectangle_sanitize (&rect, &data->area);
gtk_widget_queue_draw_area (widget, rect.x, rect.y, rect.width, rect.height);
}
#endif
data->area.width = event->x - data->area.x;
data->area.height = event->y - data->area.y;
if (data->area.x >= 0) {
cairo_rectangle_int_t rect;
rectangle_sanitize (&rect, &data->area);
gtk_widget_queue_draw_area (widget, rect.x, rect.y, rect.width, rect.height);
}
return TRUE;
}
static void
realize_cb (GtkWidget *widget, gpointer datap)
{
GdkWindow *window = gtk_widget_get_window (widget);
GdkCursor *cursor;
gdk_window_set_events (window, gdk_window_get_events (window) |
GDK_BUTTON_PRESS_MASK |
GDK_BUTTON_RELEASE_MASK |
GDK_POINTER_MOTION_MASK);
cursor = gdk_cursor_new (GDK_CROSSHAIR);
gdk_window_set_cursor (window, cursor);
g_object_unref (cursor);
gdk_window_set_background_pattern (window, NULL);
}
static void
delete_cb (GtkWidget *widget, ByzanzSelectData *data)
{
byzanz_select_done (data, NULL);
}
static void
active_cb (GtkWindow *window, GParamSpec *pspec, ByzanzSelectData *data)
{
if (!gtk_window_is_active (window))
byzanz_select_done (data, NULL);
}
static void
byzanz_select_area (ByzanzSelectData *data)
{
GdkVisual *visual;
data->window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
data->area.x = -1;
data->area.y = -1;
visual = gdk_screen_get_rgba_visual (gdk_screen_get_default ());
if (visual && gdk_screen_is_composited (gdk_screen_get_default ())) {
gtk_widget_set_visual (data->window, visual);
} else {
GdkWindow *root = gdk_get_default_root_window ();
cairo_t *cr;
cairo_surface_t *root_surface;
gint width, height;
width = gdk_window_get_width (root);
height = gdk_window_get_height (root);
cr = gdk_cairo_create (root);
root_surface = cairo_surface_reference (cairo_get_target (cr));
cairo_destroy (cr);
data->root = cairo_surface_create_similar (root_surface, CAIRO_CONTENT_COLOR, width, height);
cr = cairo_create (data->root);
cairo_set_source_surface (cr, root_surface, 0, 0);
cairo_paint (cr);
cairo_destroy (cr);
cairo_surface_destroy (root_surface);
}
gtk_widget_set_app_paintable (data->window, TRUE);
gtk_window_fullscreen (GTK_WINDOW (data->window));
g_signal_connect (data->window, "expose-event", G_CALLBACK (expose_cb), data);
g_signal_connect (data->window, "button-press-event", G_CALLBACK (button_pressed_cb), data);
g_signal_connect (data->window, "button-release-event", G_CALLBACK (button_released_cb), data);
g_signal_connect (data->window, "motion-notify-event", G_CALLBACK (motion_notify_cb), data);
g_signal_connect (data->window, "delete-event", G_CALLBACK (delete_cb), data);
g_signal_connect (data->window, "notify::is-active", G_CALLBACK (active_cb), data);
g_signal_connect_after (data->window, "realize", G_CALLBACK (realize_cb), data);
gtk_widget_show_all (data->window);
}
/*** WHOLE SCREEN ***/
static void
byzanz_select_screen (ByzanzSelectData *data)
{
GdkWindow *root;
root = gdk_get_default_root_window ();
data->area.width = gdk_window_get_width (root);
data->area.height = gdk_window_get_height (root);
byzanz_select_done (data, root);
}
/*** APPLICATION WINDOW ***/
static gboolean
select_window_button_pressed_cb (GtkWidget *widget, GdkEventButton *event, gpointer datap)
{
ByzanzSelectData *data = datap;
GdkWindow *window;
gdk_device_ungrab (gdk_event_get_device ((GdkEvent*)event), event->time);
if (event->button == 1) {
Window w;
w = screenshot_find_current_window (TRUE);
if (w != None)
window = gdk_x11_window_foreign_new_for_display (gdk_display_get_default (), w);
else
window = gdk_get_default_root_window ();
gdk_window_get_root_origin (window, &data->area.x, &data->area.y);
data->area.width = gdk_window_get_width (window);
data->area.height = gdk_window_get_height (window);
g_object_unref (window);
window = gdk_get_default_root_window ();
} else {
window = NULL;
}
byzanz_select_done (data, window);
return TRUE;
}
static void
byzanz_select_window (ByzanzSelectData *data)
{
GdkCursor *cursor;
GdkWindow *window;
GdkDevice *device;
GdkDeviceManager *device_manager;
GdkDisplay *display;
cursor = gdk_cursor_new (GDK_CROSSHAIR);
data->window = gtk_invisible_new ();
g_signal_connect (data->window, "button-press-event",
G_CALLBACK (select_window_button_pressed_cb), data);
gtk_widget_show (data->window);
window = gtk_widget_get_window (data->window);
display = gdk_window_get_display (window);
device_manager = gdk_display_get_device_manager (display);
device = gdk_device_manager_get_client_pointer (device_manager);
gdk_device_grab (device, window, GDK_OWNERSHIP_NONE, FALSE, GDK_BUTTON_PRESS_MASK, cursor, GDK_CURRENT_TIME);
g_object_unref (cursor);
}
/*** API ***/
static const struct {
const char * mnemonic;
const char * description;
const char * icon_name;
const char * method_name;
void (* select) (ByzanzSelectData *data);
} methods [] = {
{ N_("Record _Desktop"), N_("Record the entire desktop"),
"byzanz-record-desktop", "screen", byzanz_select_screen },
{ N_("Record _Area"), N_("Record a selected area of the desktop"),
"byzanz-record-area", "area", byzanz_select_area },
{ N_("Record _Window"), N_("Record a selected window"),
"byzanz-record-window", "window", byzanz_select_window }
};
#define BYZANZ_METHOD_COUNT G_N_ELEMENTS(methods)
guint
byzanz_select_get_method_count (void)
{
return BYZANZ_METHOD_COUNT;
}
const char *
byzanz_select_method_get_icon_name (guint method)
{
g_return_val_if_fail (method < BYZANZ_METHOD_COUNT, NULL);
return methods[method].icon_name;
}
const char *
byzanz_select_method_get_name (guint method)
{
g_return_val_if_fail (method < BYZANZ_METHOD_COUNT, NULL);
return methods[method].method_name;
}
int
byzanz_select_method_lookup (const char *name)
{
guint i;
g_return_val_if_fail (name != NULL, -1);
for (i = 0; i < BYZANZ_METHOD_COUNT; i++) {
if (g_str_equal (name, methods[i].method_name))
return i;
}
return -1;
}
const char *
byzanz_select_method_describe (guint method)
{
g_return_val_if_fail (method < BYZANZ_METHOD_COUNT, NULL);
return _(methods[method].description);
}
const char *
byzanz_select_method_get_mnemonic (guint method)
{
g_return_val_if_fail (method < BYZANZ_METHOD_COUNT, NULL);
return _(methods[method].mnemonic);
}
void
byzanz_select_method_select (guint method,
ByzanzSelectFunc func,
gpointer func_data)
{
ByzanzSelectData *data;
g_return_if_fail (method < BYZANZ_METHOD_COUNT);
g_return_if_fail (func != NULL);
g_assert (methods[method].select != NULL);
data = g_slice_new0 (ByzanzSelectData);
data->func = func;
data->func_data = func_data;
methods[method].select (data);
}
| 12,911 |
C
|
.c
| 371 | 31.633423 | 123 | 0.68615 |
xatgithub/byzanz
| 2 | 18 | 0 |
GPL-3.0
|
9/7/2024, 2:35:06 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
16,020,989 |
byzanzselect.h
|
xatgithub_byzanz/src/byzanzselect.h
|
/* desktop session recorder
* Copyright (C) 2005 Benjamin Otte <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include <glib.h>
#include <gtk/gtk.h>
#ifndef __HAVE_BYZANZ_SELECT_H__
#define __HAVE_BYZANZ_SELECT_H__
guint byzanz_select_get_method_count (void);
const char * byzanz_select_method_describe (guint method);
const char * byzanz_select_method_get_mnemonic (guint method);
const char * byzanz_select_method_get_icon_name (guint method);
const char * byzanz_select_method_get_name (guint method);
int byzanz_select_method_lookup (const char * name);
typedef void (* ByzanzSelectFunc) (GdkWindow *window, const cairo_rectangle_int_t *area, gpointer data);
void byzanz_select_method_select (guint method,
ByzanzSelectFunc func,
gpointer data);
#endif /* __HAVE_BYZANZ_SELECT_H__ */
| 1,799 |
C
|
.c
| 33 | 48.727273 | 104 | 0.643305 |
xatgithub/byzanz
| 2 | 18 | 0 |
GPL-3.0
|
9/7/2024, 2:35:06 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
16,020,990 |
screenshot-utils.h
|
xatgithub_byzanz/src/screenshot-utils.h
|
#ifndef __SCREENSHOT_UTILS_H__
#define __SCREENSHOT_UTILS_H__
#include <gtk/gtk.h>
#include <gdk/gdkx.h>
Window screenshot_find_current_window (gboolean include_decoration);
#endif /* __SCREENSHOT_UTILS_H__ */
| 217 |
C
|
.c
| 6 | 34.666667 | 72 | 0.730769 |
xatgithub/byzanz
| 2 | 18 | 0 |
GPL-3.0
|
9/7/2024, 2:35:06 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
16,020,996 |
paneltogglebutton.c
|
xatgithub_byzanz/src/paneltogglebutton.c
|
/*
* Copyright (C) 2005 by Benjamin Otte <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA.
*
$Id$
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "paneltogglebutton.h"
static GtkToggleButtonClass *parent_class = NULL;
static void
panel_toggle_button_size_request (GtkWidget *widget,
GtkRequisition *requisition)
{
GtkWidget *child;
child = gtk_bin_get_child (GTK_BIN (widget));
if (child) {
gtk_widget_size_request (child, requisition);
} else {
requisition->width = requisition->height = 0;
}
}
static void
panel_toggle_button_get_preferred_width (GtkWidget *widget,
gint *minimal_width,
gint *natural_width)
{
GtkRequisition requisition;
panel_toggle_button_size_request (widget, &requisition);
*minimal_width = *natural_width = requisition.width;
}
static void
panel_toggle_button_get_preferred_height (GtkWidget *widget,
gint *minimal_height,
gint *natural_height)
{
GtkRequisition requisition;
panel_toggle_button_size_request (widget, &requisition);
*minimal_height = *natural_height = requisition.height;
}
static void
panel_toggle_button_size_allocate (GtkWidget *widget,
GtkAllocation *allocation)
{
GtkWidget *child;
child = gtk_bin_get_child (GTK_BIN (widget));
gtk_widget_set_allocation (widget, allocation);
if (gtk_widget_get_realized (widget))
gdk_window_move_resize (gtk_button_get_event_window (GTK_BUTTON(widget)),
allocation->x, allocation->y,
allocation->width, allocation->height);
if (child)
gtk_widget_size_allocate (child, allocation);
}
static gboolean
panel_toggle_button_draw (GtkWidget *widget, cairo_t *cr)
{
GtkWidget *child = gtk_bin_get_child (GTK_BIN (widget));
GtkStateType state_type;
GtkShadowType shadow_type;
GtkAllocation allocation;
state_type = gtk_widget_get_state (widget);
/* FIXME: someone make this layout work nicely for all themes
* Currently I'm trying to imitate the volume applet's widget */
if (gtk_toggle_button_get_inconsistent (GTK_TOGGLE_BUTTON (widget))) {
if (state_type == GTK_STATE_ACTIVE)
state_type = GTK_STATE_NORMAL;
shadow_type = GTK_SHADOW_ETCHED_IN;
} else {
shadow_type = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)) ? GTK_SHADOW_IN : GTK_SHADOW_OUT;
}
if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)))
state_type = GTK_STATE_SELECTED;
/* FIXME: better detail? */
gtk_widget_get_allocation (widget, &allocation);
gtk_paint_flat_box (gtk_widget_get_style (widget), cr, state_type, shadow_type,
widget, "togglebutton", allocation.x,
allocation.y, allocation.width, allocation.height);
if (child)
gtk_container_propagate_draw (GTK_CONTAINER (widget), child, cr);
return FALSE;
}
static gboolean
panel_toggle_button_button_press (GtkWidget *widget, GdkEventButton *event)
{
if (event->button == 3 || event->button == 2)
return FALSE;
return GTK_WIDGET_CLASS (parent_class)->button_press_event (widget, event);
}
static gboolean
panel_toggle_button_button_release (GtkWidget *widget, GdkEventButton *event)
{
if (event->button == 3 || event->button == 2)
return FALSE;
return GTK_WIDGET_CLASS (parent_class)->button_release_event (widget, event);
}
static void
panel_toggle_button_class_init (PanelToggleButtonClass *class)
{
GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (class);
parent_class = g_type_class_peek_parent (class);
widget_class->get_preferred_width = panel_toggle_button_get_preferred_width;
widget_class->get_preferred_height = panel_toggle_button_get_preferred_height;
widget_class->size_allocate = panel_toggle_button_size_allocate;
widget_class->draw = panel_toggle_button_draw;
widget_class->button_press_event = panel_toggle_button_button_press;
widget_class->button_release_event = panel_toggle_button_button_release;
}
static void
panel_toggle_button_init (PanelToggleButton *toggle_button)
{
}
GType
panel_toggle_button_get_type (void)
{
static GType toggle_button_type = 0;
if (!toggle_button_type)
{
static const GTypeInfo toggle_button_info =
{
sizeof (PanelToggleButtonClass),
NULL, /* base_init */
NULL, /* base_finalize */
(GClassInitFunc) panel_toggle_button_class_init,
NULL, /* class_finalize */
NULL, /* class_data */
sizeof (PanelToggleButton),
0, /* n_preallocs */
(GInstanceInitFunc) panel_toggle_button_init,
NULL, /* value_table */
};
toggle_button_type = g_type_register_static (GTK_TYPE_TOGGLE_BUTTON, "PanelToggleButton",
&toggle_button_info, 0);
}
return toggle_button_type;
}
GtkWidget *
panel_toggle_button_new (void)
{
return GTK_WIDGET (g_object_new (PANEL_TYPE_TOGGLE_BUTTON, NULL));
}
| 5,628 |
C
|
.c
| 155 | 32.16129 | 109 | 0.710861 |
xatgithub/byzanz
| 2 | 18 | 0 |
GPL-3.0
|
9/7/2024, 2:35:06 PM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
16,021,000 |
record.c
|
xatgithub_byzanz/src/record.c
|
/* desktop session
* Copyright (C) 2005 Benjamin Otte <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <glib/gi18n.h>
#include "byzanzsession.h"
static int duration = 10;
static int delay = 1;
static gboolean cursor = FALSE;
static gboolean audio = FALSE;
static gboolean verbose = FALSE;
static cairo_rectangle_int_t area = { 0, 0, G_MAXINT / 2, G_MAXINT / 2 };
static GOptionEntry entries[] =
{
{ "duration", 'd', 0, G_OPTION_ARG_INT, &duration, N_("Duration of animation (default: 10 seconds)"), N_("SECS") },
{ "delay", 0, 0, G_OPTION_ARG_INT, &delay, N_("Delay before start (default: 1 second)"), N_("SECS") },
{ "cursor", 'c', 0, G_OPTION_ARG_NONE, &cursor, N_("Record mouse cursor"), NULL },
{ "audio", 'a', 0, G_OPTION_ARG_NONE, &audio, N_("Record audio"), NULL },
{ "x", 'x', 0, G_OPTION_ARG_INT, &area.x, N_("X coordinate of rectangle to record"), N_("PIXEL") },
{ "y", 'y', 0, G_OPTION_ARG_INT, &area.y, N_("Y coordinate of rectangle to record"), N_("PIXEL") },
{ "width", 'w', 0, G_OPTION_ARG_INT, &area.width, N_("Width of recording rectangle"), N_("PIXEL") },
{ "height", 'h', 0, G_OPTION_ARG_INT, &area.height, N_("Height of recording rectangle"), N_("PIXEL") },
{ "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, N_("Be verbose"), NULL },
{ NULL }
};
static void
verbose_print (const gchar *format, ...)
{
gchar *buffer;
va_list args;
if (!verbose)
return;
va_start (args, format);
buffer = g_strdup_vprintf (format, args);
va_end (args);
g_print ("%s", buffer);
}
static void
usage (void)
{
g_print (_("usage: %s [OPTIONS] filename\n"), g_get_prgname ());
g_print (_(" %s --help\n"), g_get_prgname ());
}
static void
session_notify_cb (ByzanzSession *session, GParamSpec *pspec, gpointer unused)
{
const GError *error = byzanz_session_get_error (session);
if (g_str_equal (pspec->name, "error")) {
g_print (_("Error during recording: %s\n"), error->message);
gtk_main_quit ();
return;
}
if (!byzanz_session_is_encoding (session)) {
verbose_print (_("Recording done.\n"));
gtk_main_quit ();
}
}
static gboolean
stop_recording (gpointer session)
{
verbose_print (_("Recording completed. Finishing encoding...\n"));
byzanz_session_stop (session);
return FALSE;
}
static gboolean
start_recording (gpointer session)
{
verbose_print (_("Recording starts. Will record %d seconds...\n"), duration / 1000);
byzanz_session_start (session);
g_timeout_add (duration, stop_recording, session);
return FALSE;
}
static gboolean
clamp_to_window (cairo_rectangle_int_t *out, GdkWindow *window, cairo_rectangle_int_t *in)
{
cairo_rectangle_int_t window_area = { 0, };
window_area.width = gdk_window_get_width (window);
window_area.height = gdk_window_get_height (window);
return gdk_rectangle_intersect ((GdkRectangle *) in,
(GdkRectangle *) &window_area,
(GdkRectangle *) in);
}
int
main (int argc, char **argv)
{
ByzanzSession *rec;
GOptionContext* context;
GError *error = NULL;
GFile *file;
g_set_prgname (argv[0]);
#ifdef GETTEXT_PACKAGE
bindtextdomain (GETTEXT_PACKAGE, GNOMELOCALEDIR);
bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
textdomain (GETTEXT_PACKAGE);
#endif
context = g_option_context_new (_("record your current desktop session"));
#ifdef GETTEXT_PACKAGE
g_option_context_set_translation_domain(context, GETTEXT_PACKAGE);
#endif
g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
g_option_context_add_group (context, gtk_get_option_group (TRUE));
if (!g_option_context_parse (context, &argc, &argv, &error)) {
g_print (_("Wrong option: %s\n"), error->message);
usage ();
return 1;
}
if (argc != 2) {
usage ();
return 0;
}
if (!clamp_to_window (&area, gdk_get_default_root_window (), &area)) {
g_print (_("Given area is not inside desktop.\n"));
return 1;
}
file = g_file_new_for_commandline_arg (argv[1]);
rec = byzanz_session_new (file, byzanz_encoder_get_type_from_file (file),
gdk_get_default_root_window (), &area, cursor, audio);
g_object_unref (file);
g_signal_connect (rec, "notify", G_CALLBACK (session_notify_cb), NULL);
delay = MAX (delay, 1);
delay = (delay - 1) * 1000;
duration = MAX (duration, 0);
duration *= 1000;
g_timeout_add (delay, start_recording, rec);
gtk_main ();
g_object_unref (rec);
return 0;
}
| 5,240 |
C
|
.c
| 145 | 33 | 117 | 0.674837 |
xatgithub/byzanz
| 2 | 18 | 0 |
GPL-3.0
|
9/7/2024, 2:35:06 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
16,021,001 |
playback.c
|
xatgithub_byzanz/src/playback.c
|
/* desktop session recorder
* Copyright (C) 2009 Benjamin Otte <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <glib/gi18n.h>
#include "byzanzencoder.h"
#include "byzanzserialize.h"
static GOptionEntry entries[] =
{
{ NULL }
};
static void
usage (void)
{
g_print (_("usage: %s [OPTIONS] INFILE OUTFILE\n"), g_get_prgname ());
g_print (_(" %s --help\n"), g_get_prgname ());
}
static void
encoder_notify (ByzanzEncoder *encoder, GParamSpec *pspec, GMainLoop *loop)
{
const GError *error;
error = byzanz_encoder_get_error (encoder);
if (error) {
g_print ("%s\n", error->message);
g_main_loop_quit (loop);
} else if (!byzanz_encoder_is_running (encoder)) {
g_main_loop_quit (loop);
}
}
int
main (int argc, char **argv)
{
GOptionContext* context;
GError *error = NULL;
GFile *infile;
GFile *outfile;
GInputStream *instream;
GOutputStream *outstream;
GMainLoop *loop;
ByzanzEncoder *encoder;
g_set_prgname (argv[0]);
#ifdef GETTEXT_PACKAGE
bindtextdomain (GETTEXT_PACKAGE, GNOMELOCALEDIR);
bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
textdomain (GETTEXT_PACKAGE);
#endif
g_type_init ();
context = g_option_context_new (_("process a Byzanz debug recording"));
#ifdef GETTEXT_PACKAGE
g_option_context_set_translation_domain(context, GETTEXT_PACKAGE);
#endif
g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
if (!g_option_context_parse (context, &argc, &argv, &error)) {
g_print (_("Wrong option: %s\n"), error->message);
usage ();
g_error_free (error);
return 1;
}
if (argc != 3) {
usage ();
return 0;
}
infile = g_file_new_for_commandline_arg (argv[1]);
outfile = g_file_new_for_commandline_arg (argv[2]);
loop = g_main_loop_new (NULL, FALSE);
instream = G_INPUT_STREAM (g_file_read (infile, NULL, &error));
if (instream == NULL) {
g_print ("%s\n", error->message);
g_error_free (error);
return 1;
}
outstream = G_OUTPUT_STREAM (g_file_replace (outfile, NULL,
FALSE, G_FILE_CREATE_REPLACE_DESTINATION, NULL, &error));
if (outstream == NULL) {
g_print ("%s\n", error->message);
g_error_free (error);
return 1;
}
encoder = byzanz_encoder_new (byzanz_encoder_get_type_from_file (outfile),
instream, outstream, FALSE, NULL);
g_signal_connect (encoder, "notify", G_CALLBACK (encoder_notify), loop);
g_main_loop_run (loop);
g_main_loop_unref (loop);
g_object_unref (encoder);
g_object_unref (instream);
g_object_unref (outstream);
g_object_unref (infile);
g_object_unref (outfile);
return 0;
}
| 3,388 |
C
|
.c
| 107 | 28.691589 | 76 | 0.699724 |
xatgithub/byzanz
| 2 | 18 | 0 |
GPL-3.0
|
9/7/2024, 2:35:06 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
16,021,033 |
byzanzserialize.h
|
xatgithub_byzanz/src/byzanzserialize.h
|
/* desktop session recorder
* Copyright (C) 2009 Benjamin Otte <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include <gio/gio.h>
#include <gdk/gdk.h>
#include <cairo.h>
#ifndef __HAVE_BYZANZ_SERIALIZE_H__
#define __HAVE_BYZANZ_SERIALIZE_H__
gboolean byzanz_serialize_header (GOutputStream * stream,
guint width,
guint height,
GCancellable * cancellable,
GError ** error);
gboolean byzanz_serialize (GOutputStream * stream,
guint64 msecs,
cairo_surface_t * surface,
const cairo_region_t * region,
GCancellable * cancellable,
GError ** error);
gboolean byzanz_deserialize_header (GInputStream * stream,
guint * width,
guint * height,
GCancellable * cancellable,
GError ** error);
gboolean byzanz_deserialize (GInputStream * stream,
guint64 * msecs_out,
cairo_surface_t ** surface_out,
cairo_region_t ** region_out,
GCancellable * cancellable,
GError ** error);
#endif /* __HAVE_BYZANZ_SERIALIZE_H__ */
| 2,981 |
C
|
.h
| 46 | 40.978261 | 93 | 0.413593 |
xatgithub/byzanz
| 2 | 18 | 0 |
GPL-3.0
|
9/7/2024, 2:35:06 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
16,047,794 |
check.c
|
fakechris_Atlas/tests/check/check.c
|
#include <mysql/errmsg.h>
#include <mysql/mysql.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#define MAX_LEN 1024
#define SQL_LEN 1024
#define RES_LEN 1024
int type = 0;
int n_thread = 1;
char host[MAX_LEN] = "127.0.0.1";
int port = 3306;
char user[MAX_LEN] = "";
char passwd[MAX_LEN] = "";
char sqls[MAX_LEN] = "sql_list";
int n_query = 100;
char ch[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
int n_select, n_insert, n_update;
double t_select, t_insert, t_update;
bool diff(char* line, MYSQL_ROW row, unsigned n) //比较一行结果
{
if (row == NULL) return false;
line[strlen(line)-1] = '\0'; //去除尾部的回车符
char* p = line;
char* q = strchr(p, '\t');
unsigned i = 0;
while (q != NULL)
{
*q = '\0';
if (strcmp(p, row[i]) != 0)
{
// printf("p = %s\t%lu\n", p, strlen(p));
// printf("r = %s\t%lu\n", row[i], strlen(row[i]));
return false;
}
p = q + 1;
q = strchr(p, '\t');
++i;
}
if (strcmp(p, row[i]) != 0)
{
// printf("p = %s\t%lu\n", p, strlen(p));
// printf("r = %s\t%lu\n", row[i], strlen(row[i]));
return false;
}
return true;
}
void skip(FILE* file) //跳过剩余的结果
{
char text[SQL_LEN] = {0};
while (fgets(text, SQL_LEN, file) != NULL) //读一行SQL
{
if (strcmp(text, "\n") == 0) break;
}
}
void* test_verify(void* arg)
{
//创建连接
MYSQL mysql;
mysql_init(&mysql);
if (mysql_real_connect(&mysql, host, user, passwd, NULL, port, NULL, 0) == NULL)
{
printf("Failed to connect mysql\n");
return NULL;
}
//打开SQL文件
FILE* file = fopen(sqls, "r");
if (file == NULL)
{
printf("Failed to open sql file\n");
return NULL;
}
char query[SQL_LEN];
while (fgets(query, SQL_LEN, file) != NULL) //读一行SQL
{
if (strcmp(query, "\n") == 0) continue; //读到空行,跳过
query[strlen(query)-1] = '\0'; //去除尾部的回车符
if (strcasestr(query, "use") == query) //USE DB的情况
{
struct timeval start, end;
gettimeofday(&start, NULL);
int ret = mysql_select_db(&mysql, query+4);
gettimeofday(&end, NULL);
double interval = (end.tv_sec - start.tv_sec)*1000 + (end.tv_usec - start.tv_usec)/1000.0;//单位ms
if (ret == 0) printf("Execute Succeed(%.3f ms): %s\n\n", interval, query);
else printf("Execute Failed(%.3f ms): %s\n\n", interval, query);
continue;
}
//执行
struct timeval start, end;
gettimeofday(&start, NULL);
if (mysql_query(&mysql, query) != 0)
{
char msg[RES_LEN];
if (fgets(msg, SQL_LEN, file) != NULL && strcasecmp(msg, "error\n") == 0) printf("Execute Blocked: %s\n\n", query);
else printf("Execute Failed: %s\n\n", query);
continue;
}
gettimeofday(&end, NULL);
double interval = (end.tv_sec - start.tv_sec)*1000 + (end.tv_usec - start.tv_usec)/1000.0; //单位ms
//对比结果
MYSQL_RES* result = mysql_store_result(&mysql);
if (result != NULL) //SELECT语句
{
// printf("num = %llu\n", mysql_num_rows(result));
bool not_equal = false;
char line[RES_LEN];
while (fgets(line, RES_LEN, file) != NULL && strcmp(line, "\n") != 0)
{
MYSQL_ROW row = mysql_fetch_row(result);
if (diff(line, row, mysql_num_fields(result)) == false) //某一行结果不一致
{
not_equal = true;
break;
}
}
if (not_equal == true)
{
printf("Result Incorrect(%.3f ms): %s\n\n", interval, query);
skip(file);
}
else
{
if (mysql_fetch_row(result) != NULL) //实际结果行数多于预料
{
printf("Result Incorrect(%.3f ms): %s\n\n", interval, query);
}
else //实际结果与预料行数相等且每行都相同
{
printf("Result Correct(%.3f ms): %s\n\n", interval, query);
}
}
mysql_free_result(result);
}
else //INSERT或UPDATE语句
{
printf("Result Correct(%.3f ms): %s\n\n", interval, query);
}
}
//清理
fclose(file);
mysql_close(&mysql);
return NULL;
}
void print_error(MYSQL mysql, char* query)
{
switch (mysql_errno(&mysql))
{
case CR_COMMANDS_OUT_OF_SYNC:
printf("CR_COMMANDS_OUT_OF_SYNC: ");
break;
case CR_SERVER_GONE_ERROR:
printf("CR_SERVER_GONE_ERROR: ");
break;
case CR_SERVER_LOST:
printf("CR_SERVER_LOST: ");
break;
case CR_UNKNOWN_ERROR:
printf("CR_UNKNOWN_ERROR: ");
break;
}
printf("%s\n\n", query);
exit(3);
}
void* test_short(void* arg)
{
//创建连接
MYSQL mysql;
mysql_init(&mysql);
char query[SQL_LEN];
char name[17];
name[16] = '\0';
for (int i = 0; i < n_query; ++i)
{
if (mysql_real_connect(&mysql, host, user, passwd, NULL, port, NULL, 0) == NULL)
{
printf("Failed to connect mysql\n");
return NULL;
}
//随机生成一条SQL
int mode = rand() % 6;
switch (mode)
{
case 0: //SELECT
case 1:
case 2:
case 3:
sprintf(query, "SELECT * FROM person.mytable WHERE id = %d", rand());
++n_select;
break;
case 4: //INSERT
for (int j = 0; j < 16; ++j)
{
name[j] = ch[rand() % 16];
}
sprintf(query, "INSERT INTO person.mytable VALUES (%d, '%s')", rand(), name);
++n_insert;
break;
case 5: //UPDATE
for (int j = 0; j < 16; ++j)
{
name[j] = ch[rand() % 16];
}
sprintf(query, "UPDATE person.mytable SET name = '%s' WHERE id = %d", name, rand());
++n_update;
break;
}
//mysql_query
// printf("%s\n", query);
struct timeval start, end;
gettimeofday(&start, NULL);
if (mysql_query(&mysql, query) != 0)
{
print_error(mysql, query);
}
gettimeofday(&end, NULL);
double interval = (end.tv_sec - start.tv_sec)*1000 + (end.tv_usec - start.tv_usec)/1000.0;//单位ms
if (mode <= 3) t_select += interval;
else if (mode == 4) t_insert += interval;
else t_update += interval;
mysql_close(&mysql);
}
return NULL;
}
void* test_long(void* arg)
{
//创建连接
MYSQL mysql;
mysql_init(&mysql);
if (mysql_real_connect(&mysql, host, user, passwd, NULL, port, NULL, 0) == NULL)
{
printf("Failed to connect mysql\n");
return NULL;
}
if (mysql_select_db(&mysql, "person") != 0)
{
printf("Failed to use db\n");
return NULL;
}
char query[SQL_LEN];
char name[17];
name[16] = '\0';
for (int i = 0; i < n_query; ++i)
{
//随机生成一条SQL
int mode = rand() % 6;
switch (mode)
{
case 0: //SELECT
case 1:
case 2:
case 3:
sprintf(query, "SELECT * FROM mytable WHERE id = %d", rand());
++n_select;
break;
case 4: //INSERT
for (int j = 0; j < 16; ++j)
{
name[j] = ch[rand() % 16];
}
sprintf(query, "INSERT INTO mytable VALUES (%d, '%s')", rand(), name);
++n_insert;
break;
case 5: //UPDATE
for (int j = 0; j < 16; ++j)
{
name[j] = ch[rand() % 16];
}
sprintf(query, "UPDATE mytable SET name = '%s' WHERE id = %d", name, rand());
++n_update;
break;
}
//mysql_query
// printf("%s\n", query);
struct timeval start, end;
gettimeofday(&start, NULL);
if (mysql_query(&mysql, query) != 0)
{
print_error(mysql, query);
}
gettimeofday(&end, NULL);
double interval = (end.tv_sec - start.tv_sec)*1000 + (end.tv_usec - start.tv_usec)/1000.0;//单位ms
if (mode <= 3)
{
mysql_free_result(mysql_use_result(&mysql));
t_select += interval;
}
else if (mode == 4)
{
t_insert += interval;
}
else
{
t_update += interval;
}
}
mysql_close(&mysql);
return NULL;
}
bool get_options(int argc, char** argv)
{
int n = 0;
for (int i = 1; i < argc-1; ++i)
{
if (argv[i][0] == '-')
{
char ch = argv[i][1];
if (ch == '\0') return false;
char* p = argv[i]+2;
if (*p == '\0')
{
p = argv[++i];
}
switch(ch)
{
case 't':
if (strcasecmp(p, "verify") == 0) type = 1;
else if (strcasecmp(p, "short") == 0) type = 2;
else if (strcasecmp(p, "long") == 0) type = 3;
else return false;
n |= 1;
break;
case 'c':
n_thread = atoi(p);
n |= 2;
break;
case 'h':
strcpy(host, p);
n |= 4;
break;
case 'P':
port = atoi(p);
n |= 8;
break;
case 'u':
strcpy(user, p);
n |= 16;
break;
case 'p':
strcpy(passwd, p);
n |= 32;
break;
case 'f':
strcpy(sqls, p);
break;
case 'n':
n_query = atoi(p);
break;
default:
return false;
}
}
}
/*
printf("type = %s\n", type);
printf("n_thread = %d\n", n_thread);
printf("host = %s\n", host);
printf("port = %d\n", port);
printf("user = %s\n", user);
printf("pwd = %s\n", passwd);
printf("sqls = %s\n", sqls);
*/
if (n != 63) return false;
return true;
}
int main(int argc, char** argv)
{
if (get_options(argc, argv) == false)
{
printf("usage: %s -t verify|performance -c threads -h host -P port -u username -p password -f sql_file\n", argv[0]);
printf("example: %s -t verify -c 10 -h 127.0.0.1 -P 4040 -u qtbuser -p qihoo.net -f sql_list\n", argv[0]);
return 1;
}
struct timeval tp;
gettimeofday(&tp, NULL);
srand(tp.tv_usec);
char kind[8];
void* (*func)(void*);
switch (type)
{
case 1:
strcpy(kind, "VERIFY");
func = test_verify;
break;
case 2:
strcpy(kind, "SHORT CONNECTION");
func = test_short;
break;
case 3:
strcpy(kind, "LONG CONNECTION");
func = test_long;
break;
}
n_select = n_insert = n_update = 0;
t_select = t_insert = t_update = 0;
printf("\n*************** TEST OF %s START ***************\n\n", kind);
if (type == 1) n_thread = 1;
pthread_t tid[n_thread];
for (int i = 0; i < n_thread; ++i)
{
if (pthread_create(tid+i, NULL, func, NULL) != 0)
{
printf("failed to create thread\n");
return 2;
}
}
for (int i = 0; i < n_thread; ++i)
{
pthread_join(tid[i], NULL);
}
if (type != 1)
{
printf("Overall time: %.3f ms\n", t_select + t_insert + t_update);
printf("Num of queries: %d\n", n_thread * n_query);
printf("Average latency: %.3f ms\n\n", (t_select + t_insert + t_update) / n_thread / n_query);
printf("Time of SELECTs: %.3f ms\n", t_select);
printf("Num of SELECTs: %d\n", n_select);
printf("Average latency of SELECTs: %.3f ms\n\n", t_select / n_select);
printf("Time of INSERTs: %.3f ms\n", t_insert);
printf("Num of INSERTs: %d\n", n_insert);
printf("Average latency of INSERTs: %.3f ms\n\n", t_insert / n_insert);
printf("Time of UPDATEs: %.3f ms\n", t_update);
printf("Num of UPDATEs: %d\n", n_update);
printf("Average latency of UPDATEs: %.3f ms\n\n", t_update / n_update);
}
printf("*************** TEST OF %s END ***************\n\n", kind);
return 0;
}
| 10,371 |
C
|
.c
| 431 | 20.707657 | 119 | 0.591492 |
fakechris/Atlas
| 2 | 165 | 0 |
GPL-2.0
|
9/7/2024, 2:35:33 PM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
16,047,831 |
network-backend-lua.c
|
fakechris_Atlas/src/network-backend-lua.c
|
/* $%BEGINLICENSE%$
Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; version 2 of the
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
$%ENDLICENSE%$ */
#include <lua.h>
#include "lua-env.h"
#include "glib-ext.h"
#define C(x) x, sizeof(x) - 1
#define S(x) x->str, x->len
#include "network-backend.h"
#include "network-mysqld.h"
#include "network-conn-pool-lua.h"
#include "network-backend-lua.h"
#include "network-address-lua.h"
#include "network-mysqld-lua.h"
/**
* get the info about a backend
*
* proxy.backend[0].
* connected_clients => clients using this backend
* address => ip:port or unix-path of to the backend
* state => int(BACKEND_STATE_UP|BACKEND_STATE_DOWN)
* type => int(BACKEND_TYPE_RW|BACKEND_TYPE_RO)
*
* @return nil or requested information
* @see backend_state_t backend_type_t
*/
static int proxy_backend_get(lua_State *L) {
network_backend_t *backend = *(network_backend_t **)luaL_checkself(L);
gsize keysize = 0;
const char *key = luaL_checklstring(L, 2, &keysize);
if (strleq(key, keysize, C("connected_clients"))) {
lua_pushinteger(L, backend->connected_clients);
} else if (strleq(key, keysize, C("dst"))) {
network_address_lua_push(L, backend->addr);
} else if (strleq(key, keysize, C("state"))) {
lua_pushinteger(L, backend->state);
} else if (strleq(key, keysize, C("type"))) {
lua_pushinteger(L, backend->type);
} else if (strleq(key, keysize, C("uuid"))) {
if (backend->uuid->len) {
lua_pushlstring(L, S(backend->uuid));
} else {
lua_pushnil(L);
}
} else if (strleq(key, keysize, C("weight"))) {
lua_pushinteger(L, backend->weight);
} else {
lua_pushnil(L);
}
return 1;
}
static int proxy_backend_set(lua_State *L) {
network_backend_t *backend = *(network_backend_t **)luaL_checkself(L);
gsize keysize = 0;
const char *key = luaL_checklstring(L, 2, &keysize);
if (strleq(key, keysize, C("state"))) {
backend->state = lua_tointeger(L, -1);
} else if (strleq(key, keysize, C("uuid"))) {
if (lua_isstring(L, -1)) {
size_t s_len = 0;
const char *s = lua_tolstring(L, -1, &s_len);
g_string_assign_len(backend->uuid, s, s_len);
} else if (lua_isnil(L, -1)) {
g_string_truncate(backend->uuid, 0);
} else {
return luaL_error(L, "proxy.global.backends[...].%s has to be a string", key);
}
} else {
return luaL_error(L, "proxy.global.backends[...].%s is not writable", key);
}
return 1;
}
int network_backend_lua_getmetatable(lua_State *L) {
static const struct luaL_reg methods[] = {
{ "__index", proxy_backend_get },
{ "__newindex", proxy_backend_set },
{ NULL, NULL },
};
return proxy_getmetatable(L, methods);
}
/**
* get proxy.global.backends[ndx]
*
* get the backend from the array of mysql backends.
*
* @return nil or the backend
* @see proxy_backend_get
*/
static int proxy_backends_get(lua_State *L) {
network_backend_t *backend;
network_backend_t **backend_p;
network_backends_t *bs = *(network_backends_t **)luaL_checkself(L);
int backend_ndx = luaL_checkinteger(L, 2) - 1; /** lua is indexes from 1, C from 0 */
/* check that we are in range for a _int_ */
if (NULL == (backend = network_backends_get(bs, backend_ndx))) {
lua_pushnil(L);
return 1;
}
backend_p = lua_newuserdata(L, sizeof(backend)); /* the table underneath proxy.global.backends[ndx] */
*backend_p = backend;
network_backend_lua_getmetatable(L);
lua_setmetatable(L, -2);
return 1;
}
/**
* set proxy.global.backends.addslave
*
* add slave server into mysql backends
*
* @return nil or the backend
*/
static int proxy_backends_set(lua_State *L) {
network_backend_t *bs = *(network_backend_t **)luaL_checkself(L);
gsize keysize = 0;
const char *key = luaL_checklstring(L, 2, &keysize);
if (strleq(key, keysize, C("addslave"))) {
network_backends_add(bs, g_strdup(lua_tostring(L, -1)), BACKEND_TYPE_RO);
} else if (strleq(key, keysize, C("addmaster"))) {
network_backends_add(bs, g_strdup(lua_tostring(L, -1)), BACKEND_TYPE_RW);
} else if (strleq(key, keysize, C("removebackend"))) {
network_backends_remove(bs, lua_tointeger(L, -1));
} else {
return luaL_error(L, "proxy.global.backends.%s is not writable", key);
}
return 1;
}
static int proxy_backends_len(lua_State *L) {
network_backends_t *bs = *(network_backends_t **)luaL_checkself(L);
lua_pushinteger(L, network_backends_count(bs));
return 1;
}
int network_backends_lua_getmetatable(lua_State *L) {
static const struct luaL_reg methods[] = {
{ "__index", proxy_backends_get },
{ "__newindex", proxy_backends_set },
{ "__len", proxy_backends_len },
{ NULL, NULL },
};
return proxy_getmetatable(L, methods);
}
| 5,313 |
C
|
.c
| 152 | 32.513158 | 103 | 0.68778 |
fakechris/Atlas
| 2 | 165 | 0 |
GPL-2.0
|
9/7/2024, 2:35:33 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
16,062,460 |
parser.c
|
cleech_open-isns/parser.c
|
/*
* parser.c - simple line based parser
*
* Copyright (C) 2006, 2007 Olaf Kirch <[email protected]>
*/
#include <stdlib.h>
#include <getopt.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <err.h>
#include <libisns/util.h>
/*
* By default, the parser will recognize any white space
* as "word" separators.
* If you need additional separators, you can put them
* here.
*/
const char * parser_separators = NULL;
const char * parser_punctuation = "=";
char *
parser_get_next_line(FILE *fp)
{
static char buffer[8192];
unsigned int n = 0, count = 0;
int c, continuation = 0;
while (n < sizeof(buffer) - 1) {
c = fgetc(fp);
if (c == EOF)
break;
count++;
if (c == '\r')
continue;
/* Discard all blanks
* following a backslash-newline
*/
if (continuation) {
if (c == ' ' || c == '\t')
continue;
continuation = 0;
}
if (c == '\n') {
if (n && buffer[n-1] == '\\') {
buffer[--n] = '\0';
continuation = 1;
}
while (n && isspace(buffer[n-1]))
buffer[--n] = '\0';
if (!continuation)
break;
buffer[n++] = ' ';
continue;
}
buffer[n++] = c;
}
if (count == 0)
return NULL;
buffer[n] = '\0';
return buffer;
}
static inline int
is_separator(char c)
{
if (isspace(c))
return 1;
return parser_separators && c && strchr(parser_separators, c);
}
static inline int
is_punctuation(char c)
{
return parser_punctuation && c && strchr(parser_punctuation, c);
}
char *
parser_get_next_word(char **sp)
{
static char buffer[512];
char *s = *sp, *p = buffer;
while (is_separator(*s))
++s;
if (*s == '\0')
goto done;
if (is_punctuation(*s)) {
*p++ = *s++;
goto done;
}
while (*s && !is_separator(*s) && !is_punctuation(*s))
*p++ = *s++;
done:
*p++ = '\0';
*sp = s;
return buffer[0]? buffer : NULL;
}
int
parser_split_line(char *line, unsigned int argsmax, char **argv)
{
unsigned int argc = 0;
char *s;
while (argc < argsmax && (s = parser_get_next_word(&line)))
argv[argc++] = strdup(s);
return argc;
}
char *
parser_get_rest_of_line(char **sp)
{
char *s = *sp, *res = NULL;
while (is_separator(*s))
++s;
*sp = "";
if (*s != '\0')
res = s;
return res;
}
| 2,207 |
C
|
.c
| 112 | 17.303571 | 65 | 0.612639 |
cleech/open-isns
| 2 | 28 | 0 |
LGPL-2.1
|
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
16,062,462 |
vendor.c
|
cleech_open-isns/vendor.c
|
/*
* iSNS vendor specific objects
*
* Copyright (C) 2007 Olaf Kirch <[email protected]>
*/
#include <stdlib.h>
#include <string.h>
#include <libisns/isns.h>
#include "objects.h"
#include <libisns/attrs.h>
#include "vendor.h"
#include <libisns/util.h>
static uint32_t policy_attrs[] = {
OPENISNS_TAG_POLICY_SPI,
OPENISNS_TAG_POLICY_KEY,
OPENISNS_TAG_POLICY_ENTITY,
OPENISNS_TAG_POLICY_OBJECT_TYPE,
OPENISNS_TAG_POLICY_NODE_NAME,
OPENISNS_TAG_POLICY_NODE_TYPE,
OPENISNS_TAG_POLICY_FUNCTIONS,
OPENISNS_TAG_POLICY_VISIBLE_DD,
OPENISNS_TAG_POLICY_DEFAULT_DD,
};
static uint32_t policy_key_attrs[] = {
OPENISNS_TAG_POLICY_SPI,
};
isns_object_template_t isns_policy_template = {
.iot_name = "Policy",
.iot_handle = ISNS_OBJECT_TYPE_POLICY,
.iot_attrs = policy_attrs,
.iot_num_attrs = array_num_elements(policy_attrs),
.iot_keys = policy_key_attrs,
.iot_num_keys = array_num_elements(policy_key_attrs),
.iot_container = &isns_entity_template,
.iot_vendor_specific = 1,
};
| 996 |
C
|
.c
| 36 | 25.916667 | 56 | 0.748691 |
cleech/open-isns
| 2 | 28 | 0 |
LGPL-2.1
|
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
16,062,464 |
sysdep-unix.c
|
cleech_open-isns/sysdep-unix.c
|
/*
* System dependent stuff
*
* Copyright (C) 2007 Olaf Kirch <[email protected]>
*/
#include <net/if.h>
#include <sys/ioctl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <libisns/isns.h>
#include <libisns/util.h>
int isns_get_nr_portals(void)
{
char buffer[8192], *end, *ptr;
struct ifconf ifc;
unsigned int nportals = 0;
int fd = -1;
if ((fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
isns_error("%s: no socket - %m\n", __FUNCTION__);
return 0;
}
ifc.ifc_buf = buffer;
ifc.ifc_len = sizeof(buffer);
if (ioctl(fd, SIOCGIFCONF, &ifc) < 0) {
isns_error("ioctl(SIOCGIFCONF): %m\n");
goto out;
}
ptr = buffer;
end = buffer + ifc.ifc_len;
while (ptr < end) {
struct ifreq ifr;
struct sockaddr_storage ifaddr;
int ifflags;
memcpy(&ifr, ptr, sizeof(ifr));
ptr += sizeof(ifr);
/* Get the interface addr */
memcpy(&ifaddr, &ifr.ifr_addr, sizeof(ifr.ifr_addr));
if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0) {
isns_error("ioctl(%s, SIOCGIFFLAGS): %m\n",
ifr.ifr_name);
continue;
}
ifflags = ifr.ifr_flags;
if ((ifflags & IFF_UP) == 0)
continue;
if ((ifflags & IFF_LOOPBACK) != 0)
continue;
if (ifaddr.ss_family == AF_INET6 || ifaddr.ss_family == AF_INET)
nportals++;
}
out:
if (fd >= 0)
close(fd);
return nportals;
}
int
isns_enumerate_portals(isns_portal_info_t *result, unsigned int max)
{
char buffer[8192], *end, *ptr;
struct ifconf ifc;
unsigned int nportals = 0;
int fd = -1;
if ((fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
isns_error("%s: no socket - %m\n", __FUNCTION__);
return 0;
}
ifc.ifc_buf = buffer;
ifc.ifc_len = sizeof(buffer);
if (ioctl(fd, SIOCGIFCONF, &ifc) < 0) {
isns_error("ioctl(SIOCGIFCONF): %m\n");
goto out;
}
ptr = buffer;
end = buffer + ifc.ifc_len;
while (ptr < end) {
struct ifreq ifr;
struct sockaddr_storage ifaddr;
isns_portal_info_t portal;
int ifflags;
char *ps;
memcpy(&ifr, ptr, sizeof(ifr));
ptr += sizeof(ifr);
/* Get the interface addr */
memcpy(&ifaddr, &ifr.ifr_addr, sizeof(ifr.ifr_addr));
if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0) {
isns_error("ioctl(%s, SIOCGIFFLAGS): %m\n",
ifr.ifr_name);
continue;
}
ifflags = ifr.ifr_flags;
if ((ifflags & IFF_UP) == 0)
continue;
if ((ifflags & IFF_LOOPBACK) != 0)
continue;
if (!isns_portal_from_sockaddr(&portal, &ifaddr))
continue;
ps = isns_portal_string(&portal);
isns_debug_socket("Got interface %u: %s %s\n",
nportals, ifr.ifr_name, ps);
free(ps);
if (nportals < max)
result[nportals++] = portal;
}
out:
if (fd >= 0)
close(fd);
return nportals;
}
int
isns_portal_from_sockaddr(isns_portal_info_t *portal,
const struct sockaddr_storage *addr)
{
struct sockaddr_in6 *six;
struct sockaddr_in *sin;
memset(portal, 0, sizeof(*portal));
/* May have to convert AF_INET to AF_INET6 */
six = &portal->addr;
switch (addr->ss_family) {
case AF_INET6:
memcpy(six, addr, sizeof(*six));
break;
case AF_INET:
sin = (struct sockaddr_in *) addr;
six->sin6_family = AF_INET6;
six->sin6_addr.s6_addr32[3] = sin->sin_addr.s_addr;
six->sin6_port = sin->sin_port;
break;
default:
return 0;
}
return 1;
}
int
isns_portal_to_sockaddr(const isns_portal_info_t *portal,
struct sockaddr_storage *addr)
{
const struct sockaddr_in6 *six = &portal->addr;
struct sockaddr_in *sin;
/* Check if this is really a v4 address is disguise.
* If so, explicitly use an AF_INET socket - the
* stack may not support IPv6.
*/
if (IN6_IS_ADDR_V4MAPPED(&six->sin6_addr)
|| IN6_IS_ADDR_V4COMPAT(&six->sin6_addr)) {
sin = (struct sockaddr_in *) addr;
memset(sin, 0, sizeof(*sin));
sin->sin_family = AF_INET;
sin->sin_addr.s_addr = six->sin6_addr.s6_addr32[3];
sin->sin_port = six->sin6_port;
return sizeof(*sin);
}
/* This is the genuine article */
memcpy(addr, six, sizeof(*six));
return sizeof(*six);
}
| 3,925 |
C
|
.c
| 156 | 22.49359 | 68 | 0.660776 |
cleech/open-isns
| 2 | 28 | 0 |
LGPL-2.1
|
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
16,062,465 |
relation.c
|
cleech_open-isns/relation.c
|
/*
* iSNS object relationships
*
* Relations are used to express a connection between two
* objects. Currently, two relationship types are implemented:
*
* - portal group: this relates a storage node and a portal
* - visibility: this relates a nodes nodes that share a
* common discovery domain.
*
* Relation objects are nice for portals groups, but kind of
* awkward for DDs. A better way of expressing DD membership
* (which also allows for a fast visibility check) could be
* to store a [bit] vector of DD IDs in each storage node.
* A visibility check would amount to just doing the bitwise
* AND of two vectors, and checking for NULL. The only thing
* to take care of would be to make sure a DD object takes a
* reference on its members (this is necessary so that objects
* maintain their ID/name associations even when removed from
* the database).
*
* Aug 22 2007 - changed DD code to use bit vectors. A lot
* of code in this file is now obsolete.
*
* Copyright (C) 2007 Olaf Kirch <[email protected]>
*/
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <stdarg.h>
#include <libisns/isns.h>
#include "objects.h"
#include <libisns/util.h>
#include "db.h"
struct isns_relation_soup {
/* For now, use one plain list. For better
* scalability, we'll need a hash table or
* something similar later. */
isns_relation_list_t irs_data;
};
static void isns_relation_list_append(isns_relation_list_t *,
isns_relation_t *);
static int isns_relation_list_remove(isns_relation_list_t *,
isns_relation_t *);
isns_relation_soup_t *
isns_relation_soup_alloc(void)
{
return isns_calloc(1, sizeof(isns_relation_soup_t));
}
void
isns_relation_add(isns_relation_soup_t *soup,
isns_relation_t *rp)
{
isns_relation_list_append(&soup->irs_data, rp);
}
isns_relation_t *
isns_relation_find_edge(isns_relation_soup_t *soup,
const isns_object_t *left,
const isns_object_t *right,
unsigned int relation_type)
{
isns_relation_list_t *list = &soup->irs_data;
unsigned int i;
for (i = 0; i < list->irl_count; ++i) {
isns_relation_t *rp = list->irl_data[i];
if (rp->ir_type != relation_type)
continue;
if (rp->ir_subordinate[0].obj == left
&& rp->ir_subordinate[1].obj == right)
return rp;
if (rp->ir_subordinate[0].obj == right
&& rp->ir_subordinate[1].obj == left)
return rp;
}
return NULL;
}
void
isns_relation_get_edge_objects(isns_relation_soup_t *soup,
const isns_object_t *left,
unsigned int relation_type,
isns_object_list_t *result)
{
isns_relation_list_t *list = &soup->irs_data;
unsigned int i;
for (i = 0; i < list->irl_count; ++i) {
isns_relation_t *rp = list->irl_data[i];
if (rp->ir_type != relation_type)
continue;
if (rp->ir_object == NULL)
continue;
if (rp->ir_subordinate[0].obj == left
|| rp->ir_subordinate[1].obj == left) {
isns_object_list_append(result,
rp->ir_object);
}
}
}
void
isns_relation_halfspace(isns_relation_soup_t *soup,
const isns_object_t *left,
unsigned int relation_type,
isns_object_list_t *result)
{
isns_relation_list_t *list = &soup->irs_data;
unsigned int i;
for (i = 0; i < list->irl_count; ++i) {
isns_relation_t *rp = list->irl_data[i];
if (rp->ir_type != relation_type)
continue;
if (rp->ir_subordinate[0].obj == left) {
isns_object_list_append(result,
rp->ir_subordinate[1].obj);
} else
if (rp->ir_subordinate[1].obj == left) {
isns_object_list_append(result,
rp->ir_subordinate[0].obj);
}
}
}
int
isns_relation_exists(isns_relation_soup_t *soup,
const isns_object_t *relating_object,
const isns_object_t *left,
const isns_object_t *right,
unsigned int relation_type)
{
isns_relation_list_t *list = &soup->irs_data;
unsigned int i;
for (i = 0; i < list->irl_count; ++i) {
isns_relation_t *rp = list->irl_data[i];
if (rp->ir_type != relation_type)
continue;
if (rp->ir_object != relating_object)
continue;
if (rp->ir_subordinate[0].obj == left
&& rp->ir_subordinate[1].obj == right)
return 1;
if (rp->ir_subordinate[0].obj == right
&& rp->ir_subordinate[1].obj == left)
return 1;
}
return 0;
}
isns_object_t *
isns_relation_get_other(const isns_relation_t *rp,
const isns_object_t *this)
{
if (rp->ir_subordinate[0].obj == this)
return rp->ir_subordinate[1].obj;
if (rp->ir_subordinate[1].obj == this)
return rp->ir_subordinate[0].obj;
return NULL;
}
void
isns_relation_remove(isns_relation_soup_t *soup,
isns_relation_t *rp)
{
isns_object_release(rp->ir_object);
rp->ir_object = NULL;
isns_relation_list_remove(&soup->irs_data, rp);
}
isns_relation_t *
isns_create_relation(isns_object_t *relating_object,
unsigned int relation_type,
isns_object_t *subordinate_object1,
isns_object_t *subordinate_object2)
{
isns_relation_t *rp;
rp = isns_calloc(1, sizeof(*rp));
rp->ir_type = relation_type;
rp->ir_users = 1;
rp->ir_object = isns_object_get(relating_object);
isns_object_reference_set(&rp->ir_subordinate[0], subordinate_object1);
isns_object_reference_set(&rp->ir_subordinate[1], subordinate_object2);
#if 0
if (relating_object) {
relating_object->ie_relation = rp;
rp->ir_users++;
}
#endif
return rp;
}
void
isns_relation_sever(isns_relation_t *rp)
{
isns_object_release(rp->ir_object);
rp->ir_object = NULL;
isns_object_reference_drop(&rp->ir_subordinate[0]);
isns_object_reference_drop(&rp->ir_subordinate[1]);
}
void
isns_relation_release(isns_relation_t *rp)
{
if (--(rp->ir_users))
return;
isns_relation_sever(rp);
isns_free(rp);
}
/*
* Check whether the relation references two dead/limbo objects.
* This is used for dead PG removal.
*/
int
isns_relation_is_dead(const isns_relation_t *rel)
{
isns_object_t *left, *right;
left = rel->ir_subordinate[0].obj;
right = rel->ir_subordinate[1].obj;
if ((left->ie_flags & ISNS_OBJECT_DEAD)
&& (right->ie_flags & ISNS_OBJECT_DEAD))
return 1;
return 0;
}
void
isns_relation_list_append(isns_relation_list_t *list,
isns_relation_t *rp)
{
if ((list->irl_count % 128) == 0) {
list->irl_data = isns_realloc(list->irl_data,
(list->irl_count + 128) * sizeof(void *));
if (list->irl_data == NULL)
isns_fatal("out of memory!\n");
}
list->irl_data[list->irl_count++] = rp;
rp->ir_users++;
}
int
isns_relation_list_remove(isns_relation_list_t *list,
isns_relation_t *rp)
{
unsigned int i, count = list->irl_count;
for (i = 0; i < count; ++i) {
if (list->irl_data[i] != rp)
continue;
if (i < count - 1)
list->irl_data[i] = list->irl_data[count-1];
isns_relation_release(rp);
list->irl_count -= 1;
return 1;
}
return 0;
}
| 6,638 |
C
|
.c
| 242 | 25.07438 | 72 | 0.699025 |
cleech/open-isns
| 2 | 28 | 0 |
LGPL-2.1
|
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
16,062,466 |
query.c
|
cleech_open-isns/query.c
|
/*
* Handle iSNS Device Attribute Query
*
* Copyright (C) 2007 Olaf Kirch <[email protected]>
*/
#include <stdlib.h>
#include <string.h>
#include "config.h"
#include <libisns/isns.h>
#include <libisns/attrs.h>
#include <libisns/message.h>
#include "security.h"
#include "objects.h"
#include "db.h"
#include <libisns/util.h>
/*
* Create a query, and set the source name
*/
static isns_simple_t *
__isns_create_query(isns_source_t *source, const isns_attr_list_t *key)
{
return isns_simple_create(ISNS_DEVICE_ATTRIBUTE_QUERY, source, key);
}
isns_simple_t *
isns_create_query(isns_client_t *clnt, const isns_attr_list_t *key)
{
return __isns_create_query(clnt->ic_source, key);
}
isns_simple_t *
isns_create_query2(isns_client_t *clnt, const isns_attr_list_t *key, isns_source_t *source)
{
return __isns_create_query(source?: clnt->ic_source, key);
}
int
isns_query_request_attr_tag(isns_simple_t *qry, uint32_t tag)
{
isns_attr_list_append_nil(&qry->is_operating_attrs, tag);
return ISNS_SUCCESS;
}
int
isns_query_request_attr(isns_simple_t *qry, isns_attr_t *attr)
{
if (!ISNS_ATTR_IS_NIL(attr)) {
isns_error("Query operating attribute must be NIL\n");
return ISNS_INVALID_QUERY;
}
isns_attr_list_append_attr(&qry->is_operating_attrs, attr);
return ISNS_SUCCESS;
}
static unsigned int
isns_query_get_requested_types(const isns_attr_list_t *attrs)
{
unsigned int i, mask = 0;
for (i = 0; i < attrs->ial_count; ++i) {
uint32_t tag = attrs->ial_data[i]->ia_tag_id;
isns_object_template_t *tmpl;
tmpl = isns_object_template_find(tag);
/* Ignore unknown tags */
if (tmpl == NULL)
continue;
mask |= 1 << tmpl->iot_handle;
}
return mask;
}
/*
* Get the list of objects matching this query
*/
static int
isns_query_get_objects(isns_simple_t *qry, isns_db_t *db, isns_object_list_t *result)
{
isns_scope_t *scope = NULL;
isns_object_list_t matching = ISNS_OBJECT_LIST_INIT;
isns_attr_list_t *keys = &qry->is_message_attrs;
isns_object_template_t *query_type = NULL;
unsigned int i, qry_mask = 0;
int status;
/* 5.6.5.2
* If multiple attributes are used as the Message Key, then they
* MUST all be from the same object type (e.g., IP address and
* TCP/UDP Port are attributes of the Portal object type).
*/
for (i = 0; i < keys->ial_count; ++i) {
isns_object_template_t *tmpl;
uint32_t tag = keys->ial_data[i]->ia_tag_id;
tmpl = isns_object_template_for_tag(tag);
if (tmpl == NULL)
return ISNS_ATTRIBUTE_NOT_IMPLEMENTED;
if (query_type == NULL)
query_type = tmpl;
else if (tmpl != query_type)
return ISNS_INVALID_QUERY;
}
/*
* 5.6.5.2
* An empty Message Key field indicates the query is scoped to
* the entire database accessible by the source Node.
*/
if (keys->ial_count == 0) {
query_type = &isns_entity_template;
keys = NULL;
}
/* Policy: check whether the client is allowed to
* query this type of object. */
if (!isns_policy_validate_object_type(qry->is_policy,
query_type, qry->is_function))
return ISNS_SOURCE_UNAUTHORIZED;
/* No scope means that the source is not part of
* any discovery domain, and there's no default DD.
* Just return an empty reply. */
scope = isns_scope_for_call(db, qry);
if (scope == NULL)
return ISNS_SUCCESS;
status = isns_scope_gang_lookup(scope, query_type, keys, &matching);
if (status != ISNS_SUCCESS)
goto out;
/* Extract the mask of requested objects */
qry_mask = isns_query_get_requested_types(&qry->is_operating_attrs);
/*
* 5.6.5.2
* The DevAttrQry response message returns attributes of objects
* listed in the Operating Attributes that are related to the
* Message Key of the original DevAttrQry message.
*/
for (i = 0; i < matching.iol_count; ++i) {
isns_object_t *obj = matching.iol_data[i];
if (!isns_policy_validate_object_access(qry->is_policy,
qry->is_source, obj,
qry->is_function))
continue;
if (obj->ie_container)
isns_object_list_append(result, obj->ie_container);
isns_object_list_append(result, obj);
isns_scope_get_related(scope, obj, qry_mask, result);
}
out:
isns_object_list_destroy(&matching);
isns_scope_release(scope);
return status;
}
/*
* Create a Query Response
*/
static isns_simple_t *
isns_create_query_response(isns_server_t *srv,
const isns_simple_t *qry, const isns_object_list_t *objects)
{
const isns_attr_list_t *req_attrs = NULL;
isns_simple_t *resp;
unsigned int i;
resp = __isns_create_query(srv->is_source, &qry->is_message_attrs);
/*
* 5.7.5.2.
* If no Operating Attributes are included in the original
* query, then all Operating Attributes SHALL be returned
* in the response.
*/
if (qry->is_operating_attrs.ial_count != 0)
req_attrs = &qry->is_operating_attrs;
for (i = 0; i < objects->iol_count; ++i) {
isns_object_t *obj = objects->iol_data[i];
if (obj->ie_rebuild)
obj->ie_rebuild(obj, srv->is_db);
isns_object_get_attrlist(obj,
&resp->is_operating_attrs,
req_attrs);
}
return resp;
}
int
isns_process_query(isns_server_t *srv, isns_simple_t *call, isns_simple_t **result)
{
isns_object_list_t objects = ISNS_OBJECT_LIST_INIT;
isns_simple_t *reply = NULL;
isns_db_t *db = srv->is_db;
int status;
/* Get the objects matching the query */
status = isns_query_get_objects(call, db, &objects);
if (status != ISNS_SUCCESS)
goto done;
/* Success: build the response */
reply = isns_create_query_response(srv, call, &objects);
if (reply == NULL) {
status = ISNS_INTERNAL_ERROR;
goto done;
}
/* There's nothing in the spec that tells us what to
* return if the query matches no object.
*/
if (objects.iol_count == 0) {
status = ISNS_NO_SUCH_ENTRY;
goto done;
}
done:
isns_object_list_destroy(&objects);
*result = reply;
return status;
}
/*
* Parse the list of objects in a query response
*/
int
isns_query_response_get_objects(isns_simple_t *qry,
isns_object_list_t *result)
{
return isns_simple_response_get_objects(qry, result);
}
| 5,986 |
C
|
.c
| 206 | 26.742718 | 91 | 0.707152 |
cleech/open-isns
| 2 | 28 | 0 |
LGPL-2.1
|
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
16,062,467 |
authblock.c
|
cleech_open-isns/authblock.c
|
/*
* iSNS authentication functions
*
* Copyright (C) 2007 Olaf Kirch <[email protected]>
*/
#include <stdlib.h>
#include <string.h>
#include <libisns/isns.h>
#include <libisns/attrs.h>
#include <libisns/message.h>
#include <libisns/util.h>
/* We impose an artificial limit on the size of
* the size of the authenticator
*/
#define ISNS_SPISTR_MAX 512
int
isns_authblock_decode(buf_t *bp, struct isns_authblk *auth)
{
unsigned int avail = buf_avail(bp);
uint32_t tmp_32bit_val;
uint64_t tmp_64bit_val;
/*
* we cannot pass packed structure members from isns_authblk
* to buf_getNN() or we will get an alignment error
*/
if (!buf_get32(bp, &tmp_32bit_val))
return 0;
auth->iab_bsd = tmp_32bit_val;
if (!buf_get32(bp, &tmp_32bit_val))
return 0;
auth->iab_length = tmp_32bit_val;
if (!buf_get64(bp, &tmp_64bit_val))
return 0;
auth->iab_timestamp = tmp_64bit_val;
if (!buf_get32(bp, &tmp_32bit_val))
return 0;
auth->iab_spi_len = tmp_32bit_val;
/* Make sure the length specified by the auth block
* is reasonable. */
if (auth->iab_length < ISNS_AUTHBLK_SIZE
|| auth->iab_length > avail)
return 0;
/* This chops off any data trailing the auth block.
* It also makes sure that we detect if iab_length
* exceeds the amount of available data. */
if (!buf_truncate(bp, auth->iab_length - ISNS_AUTHBLK_SIZE))
return 0;
auth->iab_spi = buf_head(bp);
if (!buf_pull(bp, auth->iab_spi_len))
return 0;
auth->iab_sig = buf_head(bp);
auth->iab_sig_len = buf_avail(bp);
return 1;
}
int
isns_authblock_encode(buf_t *bp, const struct isns_authblk *auth)
{
if (!buf_put32(bp, auth->iab_bsd)
|| !buf_put32(bp, auth->iab_length)
|| !buf_put64(bp, auth->iab_timestamp)
|| !buf_put32(bp, auth->iab_spi_len)
|| !buf_put(bp, auth->iab_spi, auth->iab_spi_len)
|| !buf_put(bp, auth->iab_sig, auth->iab_sig_len))
return 0;
return 1;
}
| 1,903 |
C
|
.c
| 66 | 26.5 | 65 | 0.690789 |
cleech/open-isns
| 2 | 28 | 0 |
LGPL-2.1
|
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
| false | false | false | true | false | false | false | true |
16,062,469 |
server.c
|
cleech_open-isns/server.c
|
/*
* iSNS server side functions
*
* Copyright (C) 2007 Olaf Kirch <[email protected]>
*/
#include "config.h"
#include <libisns/isns.h>
#include <libisns/util.h>
#include "security.h"
#include <libisns/message.h>
static int isns_not_supported(isns_server_t *, isns_simple_t *, isns_simple_t **);
struct isns_service_ops isns_default_service_ops = {
.process_registration = isns_process_registration,
.process_query = isns_process_query,
.process_getnext = isns_process_getnext,
.process_deregistration = isns_process_deregistration,
.process_scn_registration = isns_process_scn_register,
.process_scn_deregistration = isns_process_scn_deregistration,
.process_scn_event = isns_not_supported,
.process_dd_registration = isns_process_dd_registration,
.process_dd_deregistration= isns_process_dd_deregistration,
};
struct isns_service_ops isns_callback_service_ops = {
.process_esi = isns_process_esi,
.process_scn = isns_process_scn,
};
/*
* Create a server object
*/
isns_server_t *
isns_create_server(isns_source_t *source, isns_db_t *db,
struct isns_service_ops *ops)
{
isns_server_t *srv;
if (source == NULL) {
isns_error("%s: source name not set\n", __FUNCTION__);
return NULL;
}
srv = isns_calloc(1, sizeof(*srv));
srv->is_source = isns_source_get(source);
srv->is_db = db;
srv->is_ops = ops;
return srv;
}
void
isns_server_set_scn_callback(isns_server_t *srv, isns_scn_callback_fn_t *func)
{
srv->is_scn_callback = func;
}
/*
* Try to handle transactions safely.
* This isn't perfect, because there's state outside the DB (for instance
* the DD information)
*/
static int
isns_begin_write_operation(isns_server_t *srv, isns_simple_t *msg, int *status)
{
isns_db_begin_transaction(srv->is_db);
return 1;
}
static void
isns_end_write_operation(isns_server_t *srv, isns_simple_t *msg, int *status)
{
if (*status == ISNS_SUCCESS)
isns_db_commit(srv->is_db);
else
isns_db_rollback(srv->is_db);
}
static inline int
isns_begin_read_operation(isns_server_t *srv, isns_simple_t *msg, int *status)
{
return 1;
}
static void
isns_end_read_operation(isns_server_t *srv, isns_simple_t *msg, int *status)
{
}
/*
* Process an incoming message
*/
isns_message_t *
isns_process_message(isns_server_t *srv, isns_message_t *msg)
{
struct isns_service_ops *ops = srv->is_ops;
uint16_t function = msg->im_header.i_function;
int status = ISNS_SUCCESS;
isns_simple_t *call = NULL, *reply = NULL;
isns_message_t *res_msg = NULL;
isns_db_t *db = srv->is_db;
status = isns_simple_decode(msg, &call);
if (status) {
isns_debug_message("Failed to decode %s request: %s\n",
isns_function_name(msg->im_header.i_function),
isns_strerror(status));
goto reply;
}
isns_simple_print(call, isns_debug_message);
/* Set policy and privileges based on the
* sender's identity. */
if (!(call->is_policy = isns_policy_bind(msg)))
goto err_unauthorized;
if (!isns_policy_validate_function(call->is_policy, msg))
goto err_unauthorized;
/* Checks related to the message source.
* Note - some messages do not use a source.
*/
if (call->is_source) {
/* Validate the message source. This checks whether the client
* is permitted to use this source node name.
* Beware - not all messages include a source.
*/
if (!isns_policy_validate_source(call->is_policy, call->is_source))
goto err_unauthorized;
/* This may fail if the source node isn't in the DB yet. */
isns_source_set_node(call->is_source, db);
/*
* 6.2.6. Registration Period
*
* The registration SHALL be removed from the iSNS database
* if an iSNS Protocol message is not received from the
* iSNS client before the registration period has expired.
* Receipt of any iSNS Protocol message from the iSNS client
* automatically refreshes the Entity Registration Period and
* Entity Registration Timestamp. To prevent a registration
* from expiring, the iSNS client should send an iSNS Protocol
* message to the iSNS server at intervals shorter than the
* registration period. Such a message can be as simple as a
* query for one of its own attributes, using its associated
* iSCSI Name or FC Port Name WWPN as the Source attribute.
*/
/* Thusly, we update the timestamps of all entities
* registered by this source. */
isns_entity_touch(call->is_source->is_entity);
}
/* Handle the requested function. If the function vector is
* NULL, silently discard the message. */
switch (function) {
#define DO(rw, FUNCTION, __function) \
case FUNCTION: \
if (!ops->__function) \
goto no_reply; \
\
if (!isns_begin_##rw##_operation(srv, call, &status)) \
break; \
status = ops->__function(srv, call, &reply); \
isns_end_##rw##_operation(srv, call, &status); \
break
DO(write, ISNS_DEVICE_ATTRIBUTE_REGISTER, process_registration);
DO(read, ISNS_DEVICE_ATTRIBUTE_QUERY, process_query);
DO(read, ISNS_DEVICE_GET_NEXT, process_getnext);
DO(write, ISNS_DEVICE_DEREGISTER, process_deregistration);
DO(write, ISNS_DD_REGISTER, process_dd_registration);
DO(write, ISNS_DD_DEREGISTER, process_dd_deregistration);
DO(read, ISNS_SCN_REGISTER, process_scn_registration);
DO(read, ISNS_SCN_DEREGISTER, process_scn_deregistration);
DO(read, ISNS_SCN_EVENT, process_scn_event);
DO(read, ISNS_STATE_CHANGE_NOTIFICATION, process_scn);
DO(read, ISNS_ENTITY_STATUS_INQUIRY, process_esi);
DO(read, ISNS_HEARTBEAT, process_heartbeat);
#undef DO
default:
isns_error("Function %s not supported\n",
isns_function_name(function));
status = ISNS_MESSAGE_NOT_SUPPORTED;
break;
}
reply:
/* Commit any changes to the DB before we reply */
if (db)
isns_db_sync(db);
/* Send out SCN notifications */
isns_flush_events();
if (reply != NULL) {
reply->is_function |= 0x8000;
isns_simple_print(reply, isns_debug_message);
/* Encode the whole thing */
status = isns_simple_encode_response(reply, msg, &res_msg);
}
/* No reply, or error when encoding it:
* just send the error, nothing else. */
if (res_msg == NULL) {
res_msg = isns_create_reply(msg);
if (status == ISNS_SUCCESS)
status = ISNS_INTERNAL_ERROR;
}
isns_debug_message("response status 0x%04x (%s)\n",
status, isns_strerror(status));
if (status != ISNS_SUCCESS)
isns_message_set_error(res_msg, status);
no_reply:
isns_simple_free(call);
if (reply)
isns_simple_free(reply);
return res_msg;
err_unauthorized:
status = ISNS_SOURCE_UNAUTHORIZED;
goto reply;
}
int
isns_not_supported(isns_server_t *srv, isns_simple_t *call, isns_simple_t **replyp)
{
return ISNS_MESSAGE_NOT_SUPPORTED;
}
| 6,649 |
C
|
.c
| 203 | 30.334975 | 83 | 0.720524 |
cleech/open-isns
| 2 | 28 | 0 |
LGPL-2.1
|
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
16,062,470 |
attrs.c
|
cleech_open-isns/attrs.c
|
/*
* Handle iSNS attributes and attribute lists
*
* Copyright (C) 2007 Olaf Kirch <[email protected]>
*/
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <libisns/util.h>
#include "vendor.h"
#include <libisns/attrs.h>
#include <libisns/isns.h>
/* Implementation limit - sanity checking */
#define ISNS_ATTR_MAX_LEN 8192
static void __isns_attr_set_value(isns_attr_t *, const isns_value_t *);
/*
* Allocate an attribute
*/
isns_attr_t *
isns_attr_alloc(uint32_t tag, const isns_tag_type_t *tag_type, const isns_value_t *value)
{
isns_attr_t *attr;
if (tag_type == NULL)
tag_type = isns_tag_type_by_id(tag);
attr = isns_calloc(1, sizeof(*attr));
if (!attr)
isns_fatal("Out of memory!\n");
attr->ia_users = 1;
attr->ia_tag_id = tag;
attr->ia_tag = tag_type;
__isns_attr_set_value(attr, value);
return attr;
}
isns_attr_t *
isns_attr_get(isns_attr_t *attr)
{
if (attr) {
isns_assert(attr->ia_users);
attr->ia_users++;
}
return attr;
}
void
isns_attr_release(isns_attr_t *attr)
{
const isns_attr_type_t *type;
isns_assert(attr->ia_users);
if (--(attr->ia_users))
return;
type = attr->ia_value.iv_type;
if (type->it_destroy)
type->it_destroy(&attr->ia_value);
isns_free(attr);
}
/*
* Assign a value to an attribute
*/
void
__isns_attr_set_value(isns_attr_t *attr, const isns_value_t *new_value)
{
const isns_attr_type_t *type, *old_type;
isns_value_t *old_value;
old_value = &attr->ia_value;
if (old_value == new_value)
return;
old_type = old_value->iv_type;
if (old_type && old_type->it_destroy)
old_type->it_destroy(old_value);
if (!new_value || !(type = new_value->iv_type))
type = attr->ia_tag->it_type;
/* When assigning the value to the attr, check
* whether it needs special attention. */
if (new_value) {
if (type->it_assign) {
type->it_assign(&attr->ia_value, new_value);
} else {
attr->ia_value = *new_value;
}
}
attr->ia_value.iv_type = type;
}
/*
* Compare two attributes.
* Returns non-null when attributes are the same, else 0.
*/
int
isns_attr_match(const isns_attr_t *a, const isns_attr_t *b)
{
const isns_attr_type_t *type;
if (a->ia_tag_id != b->ia_tag_id)
return 0;
/* NIL acts as a wildcard */
if (a->ia_value.iv_type == &isns_attr_type_nil
|| b->ia_value.iv_type == &isns_attr_type_nil)
return 1;
if (a->ia_value.iv_type != b->ia_value.iv_type)
return 0;
type = a->ia_value.iv_type;
if (type->it_match)
return type->it_match(&a->ia_value, &b->ia_value);
return !memcmp(&a->ia_value, &b->ia_value, sizeof(isns_value_t));
}
/*
* Lexicographical comparison of two attributes.
* Returns -1 when a is less than b, +1 when a is greater than
* b, and 0 if equal.
*/
int
isns_attr_compare(const isns_attr_t *a, const isns_attr_t *b)
{
const isns_attr_type_t *type = a->ia_value.iv_type;
isns_assert(a->ia_tag_id == b->ia_tag_id);
if (type != b->ia_value.iv_type) {
/* One of them must be NIL */
if (type == &isns_attr_type_nil)
return -1;
return 1;
}
/* If both are NIL, consider them equal */
if (type == &isns_attr_type_nil)
return 0;
/* A few types need special comparison functions, but
* most don't. The reason is, we don't care whether the
* ordering this creates is the "canonical" ordering for
* this type, eg for integers. All that matters is that
* there is some consistent ordering suitable for
* DevGetNext.
*/
if (type->it_compare)
return type->it_compare(&a->ia_value, &b->ia_value);
return memcmp(&a->ia_value, &b->ia_value, sizeof(isns_value_t));
}
/*
* Convert a string to an attribute
*/
isns_attr_t *
isns_attr_from_string(uint32_t tag, const char *string)
{
const isns_tag_type_t *tag_type;
int (*parse)(isns_value_t *, const char *);
isns_value_t value;
memset(&value, 0, sizeof(value));
tag_type = isns_tag_type_by_id(tag);
if (!tag_type)
return NULL;
parse = tag_type->it_parse;
if (parse == NULL)
parse = tag_type->it_type->it_parse;
if (!parse || !parse(&value, string))
return NULL;
return isns_attr_alloc(tag, tag_type, &value);
}
/*
* Initialize an attribute list.
*/
void
isns_attr_list_init(isns_attr_list_t *list)
{
memset(list, 0, sizeof(*list));
}
static inline void
__isns_attr_list_resize(isns_attr_list_t *list, unsigned int count)
{
unsigned int max;
max = (list->ial_count + 15) & ~15;
if (count < max)
return;
count = (count + 15) & ~15;
list->ial_data = isns_realloc(list->ial_data, count * sizeof(isns_attr_t *));
if (!list->ial_data)
isns_fatal("Out of memory!\n");
}
void
isns_attr_list_append_list(isns_attr_list_t *dst,
const isns_attr_list_t *src)
{
unsigned int i, j;
__isns_attr_list_resize(dst, dst->ial_count + src->ial_count);
j = dst->ial_count;
for (i = 0; i < src->ial_count; ++i, ++j) {
isns_attr_t *attr = src->ial_data[i];
dst->ial_data[j] = attr;
attr->ia_users++;
}
dst->ial_count = j;
}
void
isns_attr_list_copy(isns_attr_list_t *dst,
const isns_attr_list_t *src)
{
isns_attr_list_destroy(dst);
isns_attr_list_append_list(dst, src);
}
void
isns_attr_list_destroy(isns_attr_list_t *list)
{
unsigned int i;
for (i = 0; i < list->ial_count; ++i) {
isns_attr_t *attr = list->ial_data[i];
isns_attr_release(attr);
}
if (list->ial_data)
isns_free(list->ial_data);
memset(list, 0, sizeof(*list));
}
int
isns_attr_list_remove_tag(isns_attr_list_t *list, uint32_t tag)
{
unsigned int i = 0, j = 0, removed = 0;
for (i = 0; i < list->ial_count; ++i) {
isns_attr_t *attr = list->ial_data[i];
if (attr->ia_tag_id == tag) {
isns_attr_release(attr);
removed++;
} else {
list->ial_data[j++] = attr;
}
}
list->ial_count = j;
return removed;
}
/*
* Locate the given attribute in the list, remove it
* and any following attributes that have a tag from the
* @subordinate_tags list. This is used by the DDDereg
* code to remove DD members.
*/
int
isns_attr_list_remove_member(isns_attr_list_t *list,
const isns_attr_t *match,
const uint32_t *subordinate_tags)
{
unsigned int i = 0, j = 0, k, removed = 0, purging = 0;
while (i < list->ial_count) {
isns_attr_t *attr = list->ial_data[i++];
if (purging && subordinate_tags) {
for (k = 0; subordinate_tags[k]; ++k) {
if (attr->ia_tag_id == subordinate_tags[k])
goto purge_attr;
}
}
purging = 0;
if (!isns_attr_match(attr, match)) {
list->ial_data[j++] = attr;
continue;
}
purge_attr:
isns_attr_release(attr);
purging = 1;
removed++;
}
list->ial_count = j;
return removed;
}
/*
* Find the first attribute with the given tag
*/
static inline isns_attr_t *
__isns_attr_list_find(const isns_attr_list_t *list, uint32_t tag)
{
isns_attr_t *attr;
unsigned int i;
for (i = 0; i < list->ial_count; ++i) {
attr = list->ial_data[i];
if (attr->ia_tag_id == tag)
return attr;
}
return NULL;
}
/*
* Add a new attribute at the end of the list
*/
static inline void
__isns_attr_list_append_attr(isns_attr_list_t *list, isns_attr_t *attr)
{
__isns_attr_list_resize(list, list->ial_count + 1);
list->ial_data[list->ial_count++] = attr;
}
void
isns_attr_list_append_attr(isns_attr_list_t *list, isns_attr_t *attr)
{
attr->ia_users++;
__isns_attr_list_append_attr(list, attr);
}
/*
* Append an element to an attribute list
*/
static void
__isns_attr_list_append(isns_attr_list_t *list,
uint32_t tag, const isns_tag_type_t *tag_type,
const isns_value_t *value)
{
isns_attr_t *attr;
if (tag_type == NULL)
tag_type = isns_tag_type_by_id(tag);
if (value->iv_type != &isns_attr_type_nil
&& value->iv_type != tag_type->it_type) {
isns_warning("Using wrong type (%s) "
"when encoding attribute %04x (%s) - should be %s\n",
value->iv_type->it_name,
tag, tag_type->it_name,
tag_type->it_type->it_name);
}
attr = isns_attr_alloc(tag, tag_type, value);
__isns_attr_list_append_attr(list, attr);
}
/*
* Update an element to an attribute list
*/
static void
__isns_attr_list_update(isns_attr_list_t *list,
uint32_t tag, const isns_tag_type_t *tag_type,
const isns_value_t *value)
{
const isns_attr_type_t *type = value->iv_type;
isns_attr_t *attr;
if (tag_type == NULL)
tag_type = isns_tag_type_by_id(tag);
if (type != &isns_attr_type_nil
&& type != tag_type->it_type) {
isns_warning("Using wrong type (%s) "
"when encoding attribute %04x (%s) - should be %s\n",
type->it_name,
tag, tag_type->it_name,
tag_type->it_type->it_name);
}
if (tag_type->it_multiple
|| (attr = __isns_attr_list_find(list, tag)) == NULL) {
attr = isns_attr_alloc(tag, tag_type, NULL);
__isns_attr_list_append_attr(list, attr);
}
__isns_attr_set_value(attr, value);
}
/*
* Append an element to an attribute list - public interface
*/
void
isns_attr_list_append_value(isns_attr_list_t *list,
uint32_t tag, const isns_tag_type_t *tag_type,
const isns_value_t *value)
{
__isns_attr_list_append(list, tag, tag_type, value);
}
/*
* Update an element of an attribute list - public interface
*/
void
isns_attr_list_update_value(isns_attr_list_t *list,
uint32_t tag, const isns_tag_type_t *tag_type,
const isns_value_t *value)
{
__isns_attr_list_update(list, tag, tag_type, value);
}
void
isns_attr_list_update_attr(isns_attr_list_t *list,
const isns_attr_t *attr)
{
__isns_attr_list_update(list, attr->ia_tag_id,
attr->ia_tag, &attr->ia_value);
}
/*
* Replace an attribute on a list
*/
int
isns_attr_list_replace_attr(isns_attr_list_t *list,
isns_attr_t *attr)
{
unsigned int i;
for (i = 0; i < list->ial_count; ++i) {
isns_attr_t *other = list->ial_data[i];
if (other->ia_tag_id == attr->ia_tag_id) {
list->ial_data[i] = attr;
attr->ia_users++;
isns_attr_release(other);
return 1;
}
}
return 0;
}
/*
* Retrieve an element of an attribute list
*/
int
isns_attr_list_get_attr(const isns_attr_list_t *list,
uint32_t tag, isns_attr_t **result)
{
*result = __isns_attr_list_find(list, tag);
return *result != NULL;
}
int
isns_attr_list_get_value(const isns_attr_list_t *list,
uint32_t tag, isns_value_t *value)
{
isns_attr_t *attr;
if (!(attr = __isns_attr_list_find(list, tag)))
return 0;
*value = attr->ia_value;
return 1;
}
int
isns_attr_list_get_uint32(const isns_attr_list_t *list,
uint32_t tag, uint32_t *value)
{
isns_attr_t *attr;
if (!(attr = __isns_attr_list_find(list, tag))
|| !ISNS_ATTR_IS_UINT32(attr))
return 0;
*value = attr->ia_value.iv_uint32;
return 1;
}
int
isns_attr_list_get_ipaddr(const isns_attr_list_t *list,
uint32_t tag, struct in6_addr *value)
{
isns_attr_t *attr;
if (!(attr = __isns_attr_list_find(list, tag))
|| !ISNS_ATTR_IS_IPADDR(attr))
return 0;
*value = attr->ia_value.iv_ipaddr;
return 1;
}
int
isns_attr_list_get_string(const isns_attr_list_t *list,
uint32_t tag, const char **value)
{
isns_attr_t *attr;
if (!(attr = __isns_attr_list_find(list, tag))
|| !ISNS_ATTR_IS_STRING(attr))
return 0;
*value = attr->ia_value.iv_string;
return 1;
}
int
isns_attr_list_contains(const isns_attr_list_t *list,
uint32_t tag)
{
return __isns_attr_list_find(list, tag) != NULL;
}
/*
* Some attribute types have an implied ordering,
* which is needed for GetNext. This is used to
* compare two lists.
*/
/*
* Typed versions of isns_attr_list_append
*/
void
isns_attr_list_append_nil(isns_attr_list_t *list, uint32_t tag)
{
isns_value_t var = ISNS_VALUE_INIT(nil, 0);
__isns_attr_list_append(list, tag, NULL, &var);
}
void
isns_attr_list_append_string(isns_attr_list_t *list,
uint32_t tag, const char *value)
{
isns_value_t var = ISNS_VALUE_INIT(string, (char *) value);
__isns_attr_list_append(list, tag, NULL, &var);
}
void
isns_attr_list_append_uint32(isns_attr_list_t *list,
uint32_t tag, uint32_t value)
{
isns_value_t var = ISNS_VALUE_INIT(uint32, value);
__isns_attr_list_append(list, tag, NULL, &var);
}
void
isns_attr_list_append_int32(isns_attr_list_t *list,
uint32_t tag, int32_t value)
{
isns_value_t var = ISNS_VALUE_INIT(int32, value);
__isns_attr_list_append(list, tag, NULL, &var);
}
void
isns_attr_list_append_uint64(isns_attr_list_t *list,
uint32_t tag, int64_t value)
{
isns_value_t var = ISNS_VALUE_INIT(uint64, value);
__isns_attr_list_append(list, tag, NULL, &var);
}
void
isns_attr_list_append_ipaddr(isns_attr_list_t *list,
uint32_t tag, const struct in6_addr *value)
{
isns_value_t var = ISNS_VALUE_INIT(ipaddr, *value);
__isns_attr_list_append(list, tag, NULL, &var);
}
/*
* Untyped version of isns_attr_list_append and isns_attr_list_update.
* The caller must make sure that the type of @data matches the tag's type.
*/
int
isns_attr_list_append(isns_attr_list_t *list, uint32_t tag, const void *data)
{
const isns_tag_type_t *tag_type;
isns_value_t var;
if (!(tag_type = isns_tag_type_by_id(tag)))
return 0;
var.iv_type = tag_type->it_type;
if (!var.iv_type->it_set(&var, data))
return 0;
__isns_attr_list_append(list, tag, tag_type, &var);
return 1;
}
int
isns_attr_list_update(isns_attr_list_t *list, uint32_t tag, const void *data)
{
const isns_tag_type_t *tag_type;
isns_attr_type_t *type;
isns_value_t var;
if (!(tag_type = isns_tag_type_by_id(tag)))
return 0;
type = tag_type->it_type;
var.iv_type = type;
if (!type->it_set(&var, data))
return 0;
__isns_attr_list_update(list, tag, tag_type, &var);
return 1;
}
/*
* Validate the attribute list.
*/
int
isns_attr_validate(const isns_attr_t *attr,
const isns_policy_t *policy)
{
const isns_tag_type_t *tag_type;
tag_type = attr->ia_tag;
if (tag_type->it_validate == NULL)
return 1;
return tag_type->it_validate(&attr->ia_value, policy);
}
int
isns_attr_list_validate(const isns_attr_list_t *list,
const isns_policy_t *policy,
unsigned int function)
{
DECLARE_BITMAP(seen, __ISNS_TAG_MAX);
unsigned int i;
for (i = 0; i < list->ial_count; ++i) {
const isns_tag_type_t *tag_type;
isns_attr_t *attr = list->ial_data[i];
uint32_t tag = attr->ia_tag_id;
unsigned int bit;
if (attr == NULL)
return ISNS_INTERNAL_ERROR;
tag_type = attr->ia_tag;
if (tag_type == NULL)
return ISNS_INTERNAL_ERROR;
bit = tag;
if (OPENISNS_IS_PRIVATE_ATTR(tag))
bit -= OPENISNS_VENDOR_PREFIX;
if (bit >= __ISNS_TAG_MAX)
goto invalid;
if (attr->ia_value.iv_type == &isns_attr_type_nil) {
if (test_bit(seen, bit))
goto invalid;
} else
if (attr->ia_value.iv_type == tag_type->it_type) {
if (!tag_type->it_multiple && test_bit(seen, bit))
goto invalid;
if (!isns_attr_validate(attr, policy))
goto invalid;
} else {
return ISNS_INTERNAL_ERROR;
}
if (function == ISNS_DEVICE_ATTRIBUTE_REGISTER
&& tag_type->it_readonly)
goto invalid;
set_bit(seen, bit);
}
return ISNS_SUCCESS;
invalid:
switch (function) {
case ISNS_DEVICE_ATTRIBUTE_REGISTER:
return ISNS_INVALID_REGISTRATION;
case ISNS_DEVICE_DEREGISTER:
return ISNS_INVALID_DEREGISTRATION;
case ISNS_DEVICE_ATTRIBUTE_QUERY:
case ISNS_DEVICE_GET_NEXT:
return ISNS_INVALID_QUERY;
}
return ISNS_ATTRIBUTE_NOT_IMPLEMENTED;
}
/*
* Debug helper: print attribute list
*/
void
isns_attr_list_print(const isns_attr_list_t *list, isns_print_fn_t *fn)
{
unsigned int i;
for (i = 0; i < list->ial_count; ++i)
isns_attr_print(list->ial_data[i], fn);
}
char *
isns_attr_print_value(const isns_attr_t *attr, char *buffer, size_t size)
{
const isns_tag_type_t *tag_type = attr->ia_tag;
const isns_attr_type_t *type = attr->ia_value.iv_type;
if (tag_type->it_print && type == tag_type->it_type)
tag_type->it_print(&attr->ia_value, buffer, size);
else
type->it_print(&attr->ia_value, buffer, size);
return buffer;
}
void
isns_attr_print(const isns_attr_t *attr, isns_print_fn_t *fn)
{
const isns_tag_type_t *tag_type = attr->ia_tag;
const isns_attr_type_t *type = attr->ia_value.iv_type;
uint32_t tag;
char value[512], *vspec = "";
tag = attr->ia_tag_id;
if (OPENISNS_IS_PRIVATE_ATTR(tag)) {
tag -= OPENISNS_VENDOR_PREFIX;
vspec = "v";
}
fn(" %04x%1s %-12s: %s = %s\n",
tag, vspec,
type->it_name,
tag_type? tag_type->it_name : "Unknown Attribute",
isns_attr_print_value(attr, value, sizeof(value)));
}
/*
* TLV encode a single attribute
*/
int
isns_attr_encode(buf_t *bp, const isns_attr_t *attr)
{
const isns_value_t *value = &attr->ia_value;
const isns_attr_type_t *type = value->iv_type;
if (!buf_put32(bp, attr->ia_tag_id)
|| !type->it_encode(bp, value))
return ISNS_INTERNAL_ERROR;
return ISNS_SUCCESS;
}
/*
* TLV decode a single attribute
*/
int
isns_attr_decode(buf_t *bp, isns_attr_t **result)
{
isns_attr_t *attr = NULL;
isns_value_t *value;
uint32_t tag, len;
if (!buf_get32(bp, &tag)
|| !buf_get32(bp, &len))
goto msg_fmt_error;
/* Attributes MUST be word aligned */
if (len & 3)
goto msg_fmt_error;
if (len > ISNS_ATTR_MAX_LEN)
goto msg_fmt_error;
/* Allocate the attribute */
attr = isns_attr_alloc(tag, NULL, NULL);
value = &attr->ia_value;
if (len == 0)
value->iv_type = &isns_attr_type_nil;
if (!value->iv_type->it_decode(bp, len, value))
goto msg_fmt_error;
*result = attr;
return ISNS_SUCCESS;
msg_fmt_error:
isns_error("Error decoding attribute, tag=0x%04x, len=%u\n",
tag, len);
if (attr)
isns_attr_release(attr);
return ISNS_MESSAGE_FORMAT_ERROR;
}
/*
* Decode the list of TLV encoded attributes inside an
* iSNS message.
*/
static int
__isns_attr_list_decode(buf_t *bp, isns_attr_list_t *list, int delimited)
{
int status;
while (buf_avail(bp)) {
isns_attr_t *attr;
status = isns_attr_decode(bp, &attr);
if (status != ISNS_SUCCESS)
return status;
if (delimited && attr->ia_tag_id == ISNS_TAG_DELIMITER) {
isns_attr_release(attr);
break;
}
__isns_attr_list_append_attr(list, attr);
}
return ISNS_SUCCESS;
}
int
isns_attr_list_decode(buf_t *bp, isns_attr_list_t *list)
{
return __isns_attr_list_decode(bp, list, 0);
}
int
isns_attr_list_decode_delimited(buf_t *bp, isns_attr_list_t *list)
{
return __isns_attr_list_decode(bp, list, 1);
}
/*
* Remove all attributes from a list save those matching
* the given tags.
*/
void
isns_attr_list_prune(isns_attr_list_t *list,
const uint32_t *tags, unsigned int num_tags)
{
unsigned int i, j, k;
for (i = j = 0; i < list->ial_count; ++i) {
isns_attr_t *attr = list->ial_data[i];
for (k = 0; k < num_tags; ++k) {
if (attr->ia_tag_id == tags[k]) {
list->ial_data[j++] = attr;
goto next;
}
}
isns_attr_release(attr);
next: ;
}
list->ial_count = j;
}
/*
* TLV ecode the list of attributes to go with
* iSNS message.
*/
int
isns_attr_list_encode(buf_t *bp, const isns_attr_list_t *list)
{
unsigned int i, status = ISNS_SUCCESS;
for (i = 0; i < list->ial_count; ++i) {
struct isns_attr *attr = list->ial_data[i];
status = isns_attr_encode(bp, attr);
if (status)
break;
}
return status;
}
/*
* Encode the delimiter attribute
*/
int
isns_encode_delimiter(buf_t *bp)
{
uint32_t tag = 0, len = 0;
if (!buf_put32(bp, tag)
|| !buf_put32(bp, len))
return ISNS_INTERNAL_ERROR;
return ISNS_SUCCESS;
}
/*
* Padded encoding
*/
static inline int
isns_encode_padded(buf_t *bp, const void *ptr, size_t len)
{
if (!buf_put(bp, ptr, len))
return 0;
if ((len & 3) == 0)
return 1;
return buf_put(bp, "\0\0\0", 4 - (len & 3));
}
/*
* Helper functions to deal with portal information
*/
void
isns_portal_init(isns_portal_info_t *portal,
const struct sockaddr *saddr, int proto)
{
const struct sockaddr_in *sin;
memset(portal, 0, sizeof(*portal));
switch (saddr->sa_family) {
case AF_INET6:
portal->addr = *(const struct sockaddr_in6 *) saddr;
break;
case AF_INET:
sin = (const struct sockaddr_in *) saddr;
portal->addr.sin6_addr.s6_addr32[3] = sin->sin_addr.s_addr;
portal->addr.sin6_port = sin->sin_port;
portal->addr.sin6_family = AF_INET6;
break;
default:
isns_warning("Unknown address family in isns_portal_init\n");
return;
}
portal->proto = proto;
}
int
isns_portal_from_attr_list(isns_portal_info_t *portal,
uint32_t addr_tag, uint32_t port_tag,
const isns_attr_list_t *list)
{
const isns_attr_t *addr_attr = NULL, *port_attr = NULL;
unsigned int i;
for (i = 0; i + 1 < list->ial_count; ++i) {
const isns_attr_t *attr = list->ial_data[i];
if (!ISNS_ATTR_IS_IPADDR(attr))
continue;
if (addr_tag && attr->ia_tag_id != addr_tag)
continue;
addr_attr = attr;
if (port_tag == 0) {
port_attr = list->ial_data[i + 1];
goto extract_portal;
}
break;
}
/* We have a specific port tag. */
while (++i < list->ial_count) {
const isns_attr_t *attr = list->ial_data[i];
if (attr->ia_tag_id == port_tag) {
port_attr = attr;
goto extract_portal;
}
}
return 0;
extract_portal:
return isns_portal_from_attr_pair(portal,
addr_attr, port_attr);
}
int
isns_portal_from_attr_pair(isns_portal_info_t *portal,
const isns_attr_t *addr_attr,
const isns_attr_t *port_attr)
{
uint32_t portspec;
memset(portal, 0, sizeof(*portal));
portal->addr.sin6_family = AF_INET6;
if (!ISNS_ATTR_IS_IPADDR(addr_attr)
|| !ISNS_ATTR_IS_UINT32(port_attr))
return 0;
portal->addr.sin6_addr = addr_attr->ia_value.iv_ipaddr;
portspec = port_attr->ia_value.iv_uint32;
portal->addr.sin6_port = htons(portspec & 0xffff);
portal->proto = (portspec & ISNS_PORTAL_PORT_UDP_MASK)? IPPROTO_UDP : IPPROTO_TCP;
return 1;
}
int
isns_portal_to_attr_list(const isns_portal_info_t *portal,
uint32_t addr_tag, uint32_t port_tag,
isns_attr_list_t *list)
{
uint32_t portspec;
portspec = htons(portal->addr.sin6_port);
if (portal->proto == IPPROTO_UDP)
portspec |= ISNS_PORTAL_PORT_UDP_MASK;
{
isns_value_t addr_value = ISNS_VALUE_INIT(ipaddr, portal->addr.sin6_addr);
isns_value_t port_value = ISNS_VALUE_INIT(uint32, portspec);
isns_attr_list_update_value(list, addr_tag, NULL, &addr_value);
isns_attr_list_update_value(list, port_tag, NULL, &port_value);
}
return 1;
}
char *
isns_portal_string(const isns_portal_info_t *portal)
{
const struct sockaddr_in6 *six = &portal->addr;
char *bufp;
char abuf[128];
inet_ntop(six->sin6_family, &six->sin6_addr, abuf, sizeof(abuf));
if (asprintf(&bufp, "[%s]:%d/%s",
abuf, ntohs(six->sin6_port),
(portal->proto == IPPROTO_UDP)? "udp" : "tcp") < 0) {
isns_error("Error printing portal: %m\n");
return NULL;
}
return bufp;
}
int
isns_portal_is_wildcard(const isns_portal_info_t *portal)
{
return !memcmp(&portal->addr.sin6_addr,
&in6addr_any,
sizeof(struct in6_addr));
}
int
isns_portal_equal(const isns_portal_info_t *a,
const isns_portal_info_t *b)
{
if (a->proto != b->proto)
return 0;
return !memcmp(&a->addr, &b->addr, sizeof(a->addr));
}
uint32_t
isns_portal_tcpudp_port(const isns_portal_info_t *portal)
{
uint32_t port;
port = isns_addr_get_port((const struct sockaddr *) &portal->addr);
if (portal->proto == IPPROTO_UDP)
port |= ISNS_PORTAL_PORT_UDP_MASK;
return port;
}
int
isns_portal_parse(isns_portal_info_t *portal,
const char *spec,
const char *default_port)
{
struct sockaddr_storage addr;
char *copy, *psp;
int alen, proto = IPPROTO_TCP, sock_type = SOCK_STREAM;
if (spec[0] == '/') {
isns_warning("%s: no AF_LOCAL addresses for portals!\n",
__FUNCTION__);
return 0;
}
/* Look at trailing /tcp or /udp */
copy = isns_strdup(spec);
if ((psp = strrchr(copy, '/')) != NULL) {
if (!strcasecmp(psp, "/udp")) {
sock_type = SOCK_DGRAM;
proto = IPPROTO_UDP;
*psp = '\0';
} else
if (!strcasecmp(psp, "/tcp")) {
sock_type = SOCK_STREAM;
proto = IPPROTO_TCP;
*psp = '\0';
}
}
alen = isns_get_address(&addr, copy, default_port, 0, sock_type, 0);
isns_free(copy);
if (alen < 0)
return 0;
isns_portal_init(portal, (struct sockaddr *) &addr, proto);
return 1;
}
/*
* Attribute type NIL
*/
static int
isns_attr_type_nil_encode(buf_t *bp, const isns_value_t *value)
{
return buf_put32(bp, 0);
}
static int
isns_attr_type_nil_decode(buf_t *bp, size_t len, isns_value_t *value)
{
return len == 0;
}
static void
isns_attr_type_nil_print(const isns_value_t *value, char *buf, size_t size)
{
snprintf(buf, size, "<empty>");
}
static int
isns_attr_type_nil_parse(isns_value_t *value, const char *string)
{
if (string && *string)
return 0;
return 1;
}
isns_attr_type_t isns_attr_type_nil = {
.it_id = ISNS_ATTR_TYPE_NIL,
.it_name = "nil",
.it_encode = isns_attr_type_nil_encode,
.it_decode = isns_attr_type_nil_decode,
.it_print = isns_attr_type_nil_print,
.it_parse = isns_attr_type_nil_parse,
};
/*
* Attribute type UINT32
*/
static int
isns_attr_type_uint32_encode(buf_t *bp, const isns_value_t *value)
{
return buf_put32(bp, 4) && buf_put32(bp, value->iv_uint32);
}
static int
isns_attr_type_uint32_decode(buf_t *bp, size_t len, isns_value_t *value)
{
if (len != 4)
return 0;
return buf_get32(bp, &value->iv_uint32);
}
static void
isns_attr_type_uint32_print(const isns_value_t *value, char *buf, size_t size)
{
snprintf(buf, size, "%u", value->iv_uint32);
}
static int
isns_attr_type_uint32_parse(isns_value_t *value, const char *string)
{
char *end;
value->iv_uint32 = strtoul(string, &end, 0);
return *end == '\0';
}
static void
isns_attr_type_int32_print(const isns_value_t *value, char *buf, size_t size)
{
snprintf(buf, size, "%d", value->iv_uint32);
}
static int
isns_attr_type_int32_parse(isns_value_t *value, const char *string)
{
char *end;
value->iv_int32 = strtol(string, &end, 0);
return *end == '\0';
}
isns_attr_type_t isns_attr_type_uint32 = {
.it_id = ISNS_ATTR_TYPE_UINT32,
.it_name = "uint32",
.it_encode = isns_attr_type_uint32_encode,
.it_decode = isns_attr_type_uint32_decode,
.it_print = isns_attr_type_uint32_print,
.it_parse = isns_attr_type_uint32_parse,
};
isns_attr_type_t isns_attr_type_int32 = {
.it_id = ISNS_ATTR_TYPE_INT32,
.it_name = "int32",
.it_encode = isns_attr_type_uint32_encode,
.it_decode = isns_attr_type_uint32_decode,
.it_print = isns_attr_type_int32_print,
.it_parse = isns_attr_type_int32_parse,
};
/*
* 16bit min/max
*/
static int
isns_attr_type_range16_encode(buf_t *bp, const isns_value_t *value)
{
uint32_t word;
word = (value->iv_range.max << 16) | value->iv_range.min;
return buf_put32(bp, 4) && buf_put32(bp, word);
}
static int
isns_attr_type_range16_decode(buf_t *bp, size_t len, isns_value_t *value)
{
uint32_t word;
if (len != 4)
return 0;
if (!buf_get32(bp, &word))
return 0;
value->iv_range.max = word >> 16;
value->iv_range.min = word & 0xFFFF;
return 1;
}
static void
isns_attr_type_range16_print(const isns_value_t *value, char *buf, size_t size)
{
snprintf(buf, size, "[%u, %u]", value->iv_range.min, value->iv_range.max);
}
isns_attr_type_t isns_attr_type_range16 = {
.it_id = ISNS_ATTR_TYPE_RANGE16,
.it_name = "range16",
.it_encode = isns_attr_type_range16_encode,
.it_decode = isns_attr_type_range16_decode,
.it_print = isns_attr_type_range16_print,
// .it_parse = isns_attr_type_range16_parse,
};
/*
* 64bit integers
*/
static int
isns_attr_type_uint64_encode(buf_t *bp, const isns_value_t *value)
{
return buf_put32(bp, 8) && buf_put64(bp, value->iv_uint64);
}
static int
isns_attr_type_uint64_decode(buf_t *bp, size_t len, isns_value_t *value)
{
if (len != 8)
return 0;
return buf_get64(bp, &value->iv_uint64);
}
static void
isns_attr_type_uint64_print(const isns_value_t *value, char *buf, size_t size)
{
snprintf(buf, size, "%Lu", (unsigned long long) value->iv_uint64);
}
static int
isns_attr_type_uint64_parse(isns_value_t *value, const char *string)
{
char *end;
value->iv_uint64 = strtoull(string, &end, 0);
return *end == '\0';
}
isns_attr_type_t isns_attr_type_uint64 = {
.it_id = ISNS_ATTR_TYPE_UINT64,
.it_name = "uint64",
.it_encode = isns_attr_type_uint64_encode,
.it_decode = isns_attr_type_uint64_decode,
.it_print = isns_attr_type_uint64_print,
.it_parse = isns_attr_type_uint64_parse,
};
/*
* Attribute type STRING
*/
static void
isns_attr_type_string_destroy(isns_value_t *value)
{
isns_free(value->iv_string);
value->iv_string = NULL;
}
static int
isns_attr_type_string_match(const isns_value_t *a, const isns_value_t *b)
{
if (a->iv_string && b->iv_string)
return !strcmp(a->iv_string, b->iv_string);
return a->iv_string == b->iv_string;
}
static int
isns_attr_type_string_compare(const isns_value_t *a, const isns_value_t *b)
{
if (a->iv_string && b->iv_string)
return strcmp(a->iv_string, b->iv_string);
return a->iv_string? 1 : -1;
}
static int
isns_attr_type_string_encode(buf_t *bp, const isns_value_t *value)
{
uint32_t len;
len = value->iv_string? strlen(value->iv_string) + 1 : 0;
if (!buf_put32(bp, ISNS_PAD(len)))
return 0;
if (len && !isns_encode_padded(bp, value->iv_string, len))
return 0;
return 1;
}
static int
isns_attr_type_string_decode(buf_t *bp, size_t len, isns_value_t *value)
{
/* Is this legal? */
if (len == 0)
return 1;
/* The string should be NUL terminated, but
* better be safe than sorry. */
value->iv_string = isns_malloc(len + 1);
if (!buf_get(bp, value->iv_string, len)) {
isns_free(value->iv_string);
return 0;
}
value->iv_string[len] = '\0';
return 1;
}
static void
isns_attr_type_string_print(const isns_value_t *value, char *buf, size_t size)
{
if (!value->iv_string)
snprintf(buf, size, "(empty)");
else
snprintf(buf, size, "\"%s\"", value->iv_string);
}
static int
isns_attr_type_string_parse(isns_value_t *value, const char *string)
{
value->iv_string = isns_strdup(string);
return 1;
}
static void
isns_attr_type_string_assign(isns_value_t *value, const isns_value_t *new_value)
{
isns_assert(!value->iv_string);
if (new_value->iv_string)
value->iv_string = isns_strdup(new_value->iv_string);
}
isns_attr_type_t isns_attr_type_string = {
.it_id = ISNS_ATTR_TYPE_STRING,
.it_name = "string",
.it_assign = isns_attr_type_string_assign,
.it_destroy = isns_attr_type_string_destroy,
.it_match = isns_attr_type_string_match,
.it_compare = isns_attr_type_string_compare,
.it_encode = isns_attr_type_string_encode,
.it_decode = isns_attr_type_string_decode,
.it_print = isns_attr_type_string_print,
.it_parse = isns_attr_type_string_parse,
};
/*
* Attribute type IPADDR
*/
static int
isns_attr_type_ipaddr_encode(buf_t *bp, const isns_value_t *value)
{
if (!buf_put32(bp, 16)
|| !buf_put(bp, &value->iv_ipaddr, 16))
return 0;
return 1;
}
static int
isns_attr_type_ipaddr_decode(buf_t *bp, size_t len, isns_value_t *value)
{
if (len != 16)
return 0;
return buf_get(bp, &value->iv_ipaddr, 16);
}
static void
isns_attr_type_ipaddr_print(const isns_value_t *value, char *buf, size_t size)
{
const struct in6_addr *addr = &value->iv_ipaddr;
char buffer[INET6_ADDRSTRLEN + 1];
/* The standard requires IPv4 mapping, but
* some oldish implementations seem to use
* IPv4 compatible addresss. */
if (IN6_IS_ADDR_V4MAPPED(addr) || IN6_IS_ADDR_V4COMPAT(addr)) {
struct in_addr ipv4;
ipv4.s_addr = addr->s6_addr32[3];
inet_ntop(AF_INET, &ipv4, buffer, sizeof(buffer));
} else {
inet_ntop(AF_INET6, addr, buffer, sizeof(buffer));
}
snprintf(buf, size, "%s", buffer);
}
static int
isns_attr_type_ipaddr_parse(isns_value_t *value, const char *string)
{
struct in_addr addr4;
if (inet_pton(AF_INET, string, &addr4)) {
value->iv_ipaddr = in6addr_any;
value->iv_ipaddr.s6_addr32[3] = addr4.s_addr;
return 1;
}
return inet_pton(AF_INET6, string, &value->iv_ipaddr);
}
isns_attr_type_t isns_attr_type_ipaddr = {
.it_id = ISNS_ATTR_TYPE_IPADDR,
.it_name = "ipaddr",
.it_encode = isns_attr_type_ipaddr_encode,
.it_decode = isns_attr_type_ipaddr_decode,
.it_print = isns_attr_type_ipaddr_print,
.it_parse = isns_attr_type_ipaddr_parse,
};
/*
* Attribute type OPAQUE
*/
static void
isns_attr_type_opaque_assign(isns_value_t *value, const isns_value_t *new_value)
{
size_t new_len = new_value->iv_opaque.len;
isns_assert(value->iv_opaque.len == 0);
if (new_len) {
value->iv_opaque.ptr = isns_malloc(new_len);
value->iv_opaque.len = new_len;
memcpy(value->iv_opaque.ptr,
new_value->iv_opaque.ptr,
new_len);
}
}
static void
isns_attr_type_opaque_destroy(isns_value_t *value)
{
isns_free(value->iv_opaque.ptr);
value->iv_opaque.ptr = NULL;
value->iv_opaque.len = 0;
}
static int
isns_attr_type_opaque_match(const isns_value_t *a, const isns_value_t *b)
{
if (a->iv_opaque.len != b->iv_opaque.len)
return 0;
return !memcmp(a->iv_opaque.ptr, b->iv_opaque.ptr, a->iv_opaque.len);
}
static int
isns_attr_type_opaque_compare(const isns_value_t *a, const isns_value_t *b)
{
long delta;
delta = a->iv_opaque.len - b->iv_opaque.len;
if (delta)
return delta;
return memcmp(a->iv_opaque.ptr, b->iv_opaque.ptr, a->iv_opaque.len);
}
static int
isns_attr_type_opaque_encode(buf_t *bp, const isns_value_t *value)
{
uint32_t len;
len = value->iv_opaque.len;
if (len & 3)
return 0;
if (!buf_put32(bp, len)
|| !buf_put(bp, value->iv_opaque.ptr, len))
return 0;
return 1;
}
static int
isns_attr_type_opaque_decode(buf_t *bp, size_t len, isns_value_t *value)
{
value->iv_opaque.ptr = isns_malloc(len);
if (!buf_get(bp, value->iv_opaque.ptr, len)) {
isns_free(value->iv_opaque.ptr);
return 0;
}
value->iv_opaque.len = len;
return 1;
}
static void
isns_attr_type_opaque_print(const isns_value_t *value, char *buf, size_t size)
{
unsigned char *data = value->iv_opaque.ptr;
unsigned int i, len;
/* There must be room for "<...>\0" */
if (size < 6)
return;
size -= 6;
if ((len = value->iv_opaque.len) > 20)
len = 20;
if (size < 3 * len)
len = size / 3;
*buf++ = '<';
for (i = 0; i < len; ++i) {
if (i)
*buf++ = ' ';
sprintf(buf, "%02x", data[i]);
buf += 2;
}
if (len < value->iv_opaque.len) {
strcat(buf, "...");
buf += 4;
}
*buf++ = '>';
*buf++ = '\0';
}
isns_attr_type_t isns_attr_type_opaque = {
.it_id = ISNS_ATTR_TYPE_OPAQUE,
.it_name = "opaque",
.it_assign = isns_attr_type_opaque_assign,
.it_destroy = isns_attr_type_opaque_destroy,
.it_match = isns_attr_type_opaque_match,
.it_compare = isns_attr_type_opaque_compare,
.it_encode = isns_attr_type_opaque_encode,
.it_decode = isns_attr_type_opaque_decode,
.it_print = isns_attr_type_opaque_print,
};
/*
* Map attribute type IDs to attribute types
*/
static isns_attr_type_t *
isns_attr_types_builtin[__ISNS_ATTR_TYPE_BUILTIN_MAX] = {
[ISNS_ATTR_TYPE_NIL] = &isns_attr_type_nil,
[ISNS_ATTR_TYPE_OPAQUE] = &isns_attr_type_opaque,
[ISNS_ATTR_TYPE_STRING] = &isns_attr_type_string,
[ISNS_ATTR_TYPE_INT32] = &isns_attr_type_int32,
[ISNS_ATTR_TYPE_UINT32] = &isns_attr_type_uint32,
[ISNS_ATTR_TYPE_UINT64] = &isns_attr_type_uint64,
[ISNS_ATTR_TYPE_IPADDR] = &isns_attr_type_ipaddr,
[ISNS_ATTR_TYPE_RANGE16] = &isns_attr_type_range16,
};
const isns_attr_type_t *
isns_attr_type_by_id(unsigned int id)
{
if (id < __ISNS_ATTR_TYPE_BUILTIN_MAX)
return isns_attr_types_builtin[id];
/* TODO: handle dynamic registration of attrtypes
* for vendor extensions. */
return NULL;
}
| 34,972 |
C
|
.c
| 1,345 | 23.821561 | 89 | 0.683638 |
cleech/open-isns
| 2 | 28 | 0 |
LGPL-2.1
|
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
16,062,471 |
portal-group.c
|
cleech_open-isns/portal-group.c
|
/*
* iSNS object model - portal group specific code
*
* Copyright (C) 2007 Olaf Kirch <[email protected]>
*/
#include <stdlib.h>
#include <string.h>
#include <libisns/isns.h>
#include "objects.h"
#include "vendor.h"
#include <libisns/attrs.h>
#include <libisns/util.h>
/* For relationship stuff - should go */
#include "db.h"
/*
* Retrieve attribute @old_tag from object @obj, create a copy with
* tag @new_tag, and append it to list @dst.
* (Helper function for the portal group stuff)
*/
static int
__isns_object_translate_attr(isns_object_t *obj,
uint32_t old_tag, uint32_t new_tag,
isns_attr_list_t *dst)
{
isns_value_t value;
if (!isns_attr_list_get_value(&obj->ie_attrs, old_tag, &value))
return 0;
isns_attr_list_append_value(dst, new_tag, NULL, &value);
return 1;
}
/*
* Portal Group
*/
static isns_object_t *
__isns_pg_create(const isns_attr_list_t *attrs, uint32_t pg_tag,
isns_object_t *portal, isns_object_t *node)
{
isns_object_t *obj;
obj = isns_create_object(&isns_iscsi_pg_template, attrs,
isns_object_get_entity(portal));
/*
* 3.4
*
* Each Portal and iSCSI Storage Node registered in an Entity can
* be associated using a Portal Group (PG) object. The PG Tag
* (PGT), if non-NULL, indicates that the associated Portal
* provides access to the associated iSCSI Storage Node in
* the Entity. All Portals that have the same PGT value for
* a specific iSCSI Storage Node allow coordinated access to
* that node.
*
* 5.6.5.2
*
* If the PGT of the Portal Group is not NULL, then a relationship
* exists between the indicated Storage Node and Portal; if the
* PGT is NULL, then no relationship exists.
*/
if (pg_tag != 0) {
isns_object_set_uint32(obj,
ISNS_TAG_PG_TAG, pg_tag);
} else {
/* A NULL PGT indicates that the
* storage node cannot be accessed through
* this portal. */
isns_object_set_nil(obj, ISNS_TAG_PG_TAG);
}
/* This object represents a relationship between portal
and storage node. Create a relation. */
obj->ie_relation = isns_create_relation(obj,
ISNS_RELATION_PORTAL_GROUP,
portal, node);
return obj;
}
/*
* Find the portal for a given portal group
*/
static isns_object_t *
__isns_pg_find_portal(isns_db_t *db, isns_object_t *pg,
const isns_object_list_t *extra_objs)
{
isns_attr_list_t key_attrs = ISNS_ATTR_LIST_INIT;
isns_object_t *obj = NULL;
/* FIXME: ISNS_TAG_PG_PORTAL_IP_ADDR -> ...ADDRESS */
if (!__isns_object_translate_attr(pg,
ISNS_TAG_PG_PORTAL_IP_ADDR,
ISNS_TAG_PORTAL_IP_ADDRESS,
&key_attrs))
goto out;
if (!__isns_object_translate_attr(pg,
ISNS_TAG_PG_PORTAL_TCP_UDP_PORT,
ISNS_TAG_PORTAL_TCP_UDP_PORT,
&key_attrs))
goto out;
obj = isns_db_lookup(db, &isns_portal_template, &key_attrs);
if (!obj && extra_objs)
obj = isns_object_list_lookup(extra_objs,
&isns_portal_template, &key_attrs);
out:
isns_attr_list_destroy(&key_attrs);
return obj;
}
/*
* Find the node for a given portal group
*/
static isns_object_t *
__isns_pg_find_node(isns_db_t *db, isns_object_t *pg,
const isns_object_list_t *extra_objs)
{
isns_attr_list_t key_attrs = ISNS_ATTR_LIST_INIT;
isns_object_t *obj = NULL;
if (!__isns_object_translate_attr(pg,
ISNS_TAG_PG_ISCSI_NAME,
ISNS_TAG_ISCSI_NAME,
&key_attrs))
goto out;
obj = isns_db_lookup(db, &isns_iscsi_node_template, &key_attrs);
if (!obj && extra_objs)
obj = isns_object_list_lookup(extra_objs,
&isns_iscsi_node_template, &key_attrs);
out:
isns_attr_list_destroy(&key_attrs);
return obj;
}
/*
* When creating a portal group, it must not connect nodes and
* portals from other entities. However, it is perfectly fine to
* link objects in limbo.
*/
static inline int
__isns_pg_may_relate(isns_object_t *entity, isns_object_t *subordinate)
{
isns_object_t *other;
other = isns_object_get_entity(subordinate);
return other == NULL || other == entity;
}
/*
* Given a portal group object, create the relationship
*/
isns_relation_t *
isns_db_build_pg_relation(isns_db_t *db, isns_object_t *pg,
const isns_object_list_t *extra_objs)
{
isns_object_t *entity, *node = NULL, *portal = NULL;
entity = isns_object_get_entity(pg);
node = __isns_pg_find_node(db, pg, extra_objs);
if (node == NULL) {
isns_error("Trying to register PG for non-existant node\n");
goto failed;
}
if (!__isns_pg_may_relate(entity, node)) {
isns_error("Trying to register PG for node in other entity\n");
goto failed;
}
portal = __isns_pg_find_portal(db, pg, extra_objs);
if (portal == NULL) {
isns_error("Trying to register PG for non-existant portal\n");
goto failed;
}
if (!__isns_pg_may_relate(entity, portal)) {
isns_error("Trying to register PG for portal in other entity\n");
goto failed;
}
pg->ie_relation = isns_create_relation(pg,
ISNS_RELATION_PORTAL_GROUP,
node, portal);
isns_object_release(portal);
isns_object_release(node);
return pg->ie_relation;
failed:
if (portal)
isns_object_release(portal);
if (node)
isns_object_release(node);
return NULL;
}
/*
* Create a portal group given node, portal and PGT
*/
isns_object_t *
isns_create_portal_group(isns_object_t *portal,
isns_object_t *node, uint32_t pg_tag)
{
isns_attr_list_t key_attrs = ISNS_ATTR_LIST_INIT;
isns_object_t *obj = NULL;
if (portal == NULL || node == NULL)
return NULL;
if (node->ie_container != portal->ie_container) {
isns_error("Refusing to create portal group "
"linking objects from different entities\n");
return NULL;
}
if (__isns_object_translate_attr(node,
ISNS_TAG_ISCSI_NAME,
ISNS_TAG_PG_ISCSI_NAME,
&key_attrs)
&& __isns_object_translate_attr(portal,
ISNS_TAG_PORTAL_IP_ADDRESS,
ISNS_TAG_PG_PORTAL_IP_ADDR,
&key_attrs)
&& __isns_object_translate_attr(portal,
ISNS_TAG_PORTAL_TCP_UDP_PORT,
ISNS_TAG_PG_PORTAL_TCP_UDP_PORT,
&key_attrs)) {
obj = __isns_pg_create(&key_attrs, pg_tag, portal, node);
}
isns_attr_list_destroy(&key_attrs);
return obj;
}
/*
* 5.6.5.1
* New PG objects are registered when an associated Portal or
* iSCSI Node object is registered. An explicit PG object
* registration MAY follow a Portal or iSCSI Node object
* registration in a DevAttrReg message.
* [...]
* If the PGT value is not included in the Storage Node or
* Portal object registration, and if a PGT value was not
* previously registered for the relationship, then the PGT for
* the corresponding PG object SHALL be registered with a value
* of 0x00000001.
*
* We return non-NULL if the object was created.
*/
isns_object_t *
isns_create_default_portal_group(isns_db_t *db,
isns_object_t *portal, isns_object_t *node)
{
isns_object_t *obj;
if (portal == NULL || node == NULL)
return 0;
/* See if there is a PG already */
obj = isns_db_get_relationship_object(db, node, portal,
ISNS_RELATION_PORTAL_GROUP);
if (obj != NULL) {
isns_object_release(obj);
return NULL;
}
return isns_create_portal_group(portal, node, 1);
}
static uint32_t iscsi_pg_attrs[] = {
ISNS_TAG_PG_ISCSI_NAME,
ISNS_TAG_PG_PORTAL_IP_ADDR,
ISNS_TAG_PG_PORTAL_TCP_UDP_PORT,
ISNS_TAG_PG_TAG,
ISNS_TAG_PG_INDEX,
};
static uint32_t iscsi_pg_key_attrs[] = {
ISNS_TAG_PG_ISCSI_NAME,
ISNS_TAG_PG_PORTAL_IP_ADDR,
ISNS_TAG_PG_PORTAL_TCP_UDP_PORT,
};
isns_object_template_t isns_iscsi_pg_template = {
.iot_name = "iSCSI Portal Group",
.iot_handle = ISNS_OBJECT_TYPE_PG,
.iot_attrs = iscsi_pg_attrs,
.iot_num_attrs = array_num_elements(iscsi_pg_attrs),
.iot_keys = iscsi_pg_key_attrs,
.iot_num_keys = array_num_elements(iscsi_pg_key_attrs),
.iot_attrs = iscsi_pg_attrs,
.iot_keys = iscsi_pg_key_attrs,
.iot_index = ISNS_TAG_PG_INDEX,
.iot_next_index = ISNS_TAG_PG_NEXT_INDEX,
.iot_container = &isns_entity_template,
.iot_relation_type = ISNS_RELATION_PORTAL_GROUP,
.iot_build_relation = isns_db_build_pg_relation,
};
| 7,888 |
C
|
.c
| 266 | 27.184211 | 71 | 0.708877 |
cleech/open-isns
| 2 | 28 | 0 |
LGPL-2.1
|
9/7/2024, 2:35:42 PM (Europe/Amsterdam)
| false | false | false | false | false | false | false | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.