Convert all block comments to line comments.

Remove non-ascii characters from source, replace with hex printf.
Translate german comments to english.
Remove profanity from comments.
This commit is contained in:
Mike Sharov 2018-04-27 10:47:43 -04:00
parent f1a7b649f6
commit cea1dafb04
23 changed files with 1219 additions and 1279 deletions

179
about.c
View File

@ -29,7 +29,7 @@
extern struct keybindings keybindings;
extern struct color color;
/* Snowflake for the xmas about box. */
// Snowflake for the xmas about box.
struct snowflake {
int x;
int y;
@ -37,14 +37,14 @@ struct snowflake {
int oldy;
char oldchar;
char oldchar2;
int visible; /* Don't draw flakes over text. */
int vspeed; /* Vertical speed of the flake */
int hspeed; /* Horizontal speed */
int visible; // Don't draw flakes over text.
int vspeed; // Vertical speed of the flake
int hspeed; // Horizontal speed
struct snowflake * next;
struct snowflake * prev;
};
/* Santa Hunta */
// Santa Hunta
typedef struct shot {
int x;
int y;
@ -69,9 +69,10 @@ typedef struct scoreDisplay {
int rounds;
} scoreDisplay;
/* This draws the colored parts of the christmas tree.
Called everytime during SnowFall to avoid to much duplicate code.
Use sparsly as snowflakes will vanish behind this elements. */
// This draws the colored parts of the christmas tree.
// Called everytime during SnowFall to avoid to much duplicate code.
// Use sparesly as snowflakes will vanish behind this elements.
//
void ChristmasTree (void) {
attron (COLOR_PAIR(13));
mvaddch (6, 13, '&');
@ -91,60 +92,63 @@ void ChristmasTree (void) {
attroff (COLOR_PAIR(14));
}
/* This function sometimes deletes characters. Maybe oldchar doesn't
get saved correctly everytime... But who cares!? :P */
// This function sometimes deletes characters. Maybe oldchar doesn't
// get saved correctly everytime... But who cares!? :P
//
void Snowfall (int christmastree) {
struct snowflake *cur;
struct snowflake *first = NULL;
struct snowflake *new;
struct snowflake *curnext;
/* The idea behind wind:
Determine windtimer and wait that many rounds before we initially
select any windspeed. If we've waited enough rounds (windtimer==0)
select a windspeed and windtimer (which should be much less than
between the storms). Use (slightly randomly offset) windspeed to
blow snowflakes around (to left or right). If windtimer drops to 0
again select new windtimer, wait, repeat. */
//
// The idea behind wind:
//
// Determine windtimer and wait that many rounds before we initially
// select any windspeed. If we've waited enough rounds (windtimer==0)
// select a windspeed and windtimer (which should be much less than
// between the storms). Use (slightly randomly offset) windspeed to
// blow snowflakes around (to left or right). If windtimer drops to 0
// again select new windtimer, wait, repeat.
//
int windspeed = 0;
int windtimer = 0;
int wind = 1; /* 1: wind active, 0: inactive
set to 1 here so the first loop run clears it. */
int newflake = 0; /* Time until a new flake appears. */
int wind = 1; // 1: wind active, 0: inactive
// set to 1 here so the first loop run clears it.
int newflake = 0; // Time until a new flake appears.
/* Set ncurses halfdelay mode. */
halfdelay (3);
halfdelay (3); // Set ncurses halfdelay mode.
/* White snowflakes! */
/* Doesn't work on white terminal background... obviously.
attron (COLOR_PAIR(16));
attron (WA_BOLD); */
// White snowflakes!
#if 0
// Doesn't work on white terminal background... obviously.
attron (COLOR_PAIR(16));
attron (WA_BOLD);
#endif
while (1) {
/* Set up the storm. */
// Set up the storm.
if (windtimer == 0) {
if (wind) {
/* Entering silence */
if (wind) { // Entering silence
windtimer = 10 + ((float)rand() / (float)RAND_MAX * 50);
wind = 0;
windspeed = 0;
} else {
/* Entering storm. */
} else { // Entering storm.
windtimer = 10 + ((float)rand() / (float)RAND_MAX * 20);
wind = 1;
windspeed = (1+(float)rand() / (float)RAND_MAX * 11)-6;
}
}
/*
mvaddstr(2,1, " ");
if (wind)
mvprintw (2,1,"Windspeed: %d; rounds left: %d",windspeed,windtimer);
else
mvprintw (2,1,"No wind; rounds left: %d",windtimer);
*/
#if 0
mvaddstr(2,1, " ");
if (wind)
mvprintw (2,1,"Windspeed: %d; rounds left: %d",windspeed,windtimer);
else
mvprintw (2,1,"No wind; rounds left: %d",windtimer);
#endif
/* Add new snowflakes. */
// Add new snowflakes.
if (newflake == 0) {
/* Add new flake to pointer chain with random x offset. */
// Add new flake to pointer chain with random x offset.
new = malloc (sizeof (struct snowflake));
new->y = 0;
new->x = (float)rand() / (float)RAND_MAX * COLS;
@ -155,7 +159,7 @@ void Snowfall (int christmastree) {
new->vspeed = 1+(float)rand() / (float)RAND_MAX * 2;
new->hspeed = (1+(float)rand() / (float)RAND_MAX * 7)-4;
/* Add our new snowflake to the pointer chain. */
// Add our new snowflake to the pointer chain.
new->next = NULL;
if (first == NULL) {
new->prev = NULL;
@ -167,22 +171,21 @@ void Snowfall (int christmastree) {
new->prev->next = new;
}
/* Set new counter until next snowflake. */
// Set new counter until next snowflake.
newflake = 1+(float)rand() / (float)RAND_MAX * 2;
/*
mvaddstr (1,1," ");
mvprintw (1,1,"New flake in %d rounds.", newflake);
*/
#if 0
mvaddstr (1,1," ");
mvprintw (1,1,"New flake in %d rounds.", newflake);
#endif
}
for (cur = first; cur != NULL; cur = curnext) {
curnext = cur->next;
/* Draw every snowflake at its coordinates to the screen. */
// Draw every snowflake at its coordinates to the screen.
if (cur->visible) {
/* Only draw if y<=LINES. This makes some snow lie on bottom of screen. */
// Only draw if y<=LINES. This makes some snow lie on bottom of screen.
if (cur->y <= LINES) {
/* Restore old char with proper color.
See also ChristmasTree() above. */
// Restore old char with proper color. See also ChristmasTree() above.
if (((cur->oldx < 25) && (cur->oldy > 5)) ||
(cur->oldx < 20))
attron (COLOR_PAIR(11));
@ -205,13 +208,13 @@ void Snowfall (int christmastree) {
cur->oldx = cur->x;
cur->oldy = cur->y;
}
/* Set new hspeed for flake */
// Set new hspeed for flake
cur->hspeed = (1+(float)rand() / (float)RAND_MAX * 7)-4;
/* Advance every flake downwards by a random amount and to
the left or right.
Check if the next position would obscure a character on the screen
and set visible to 0 in this case. Clear visible flag as needed. */
// Advance every flake downwards by a random amount and to
// the left or right.
// Check if the next position would obscure a character on the screen
// and set visible to 0 in this case. Clear visible flag as needed.
cur->y += cur->vspeed;
if (wind)
cur->hspeed += windspeed;
@ -231,14 +234,14 @@ void Snowfall (int christmastree) {
continue;
}
/* Only draw if we're still inside the window. */
// Only draw if we're still inside the window.
if (cur->y <= LINES) {
/*
mvaddstr (3,1," ");
mvprintw (3,1,"Flake hspeed: %d",cur->hspeed);
*/
#if 0
mvaddstr (3,1," ");
mvprintw (3,1,"Flake hspeed: %d",cur->hspeed);
#endif
cur->oldchar2 = cur->oldchar;
/* Reset to ' ' if we accidently set it to *. */
// Reset to ' ' if we accidently set it to *.
if (cur->oldchar2 == '*')
cur->oldchar2 = ' ';
if ((cur->x <= COLS) && (cur->y <= LINES))
@ -253,21 +256,21 @@ void Snowfall (int christmastree) {
refresh();
/* Leave loop if anykey(tm) was pressed. */
// Leave loop if anykey(tm) was pressed.
if (getch() != ERR)
break;
}
/* Leave halfdelay mode. */
// Leave halfdelay mode.
cbreak();
}
void xmasAbout (void) {
/* Logo */
// Logo
mvaddstr (1, 0, " _____ _____ ____ _______ _____ ____ _______ _____");
mvaddstr (2, 0, " / __/ \\ \\ / __ \\\\ | | \\\\ \\ / _/ \\ | | \\ / __/");
mvaddstr (3, 0, " \\___ \\ \\ | \\ \\ \\/ / \\ / \\ | \\\\ __\\ \\ / \\___ \\");
mvaddstr (4, 0, " /____/ /_|__/ \\__/ /__|_/ /_|__/ \\___\\ /__|_/ /____/");
/* Christmas tree. */
// Christmas tree.
attron (COLOR_PAIR(11));
mvaddstr (1, 0, "");
mvaddstr (2, 0, "");
@ -299,7 +302,7 @@ void xmasAbout (void) {
mvaddstr (23, 10, "####");
attroff (COLOR_PAIR(12));
ChristmasTree();
/* Credits. */
// Credits.
mvprintw (5, 21, "Version %s", VERSION);
mvprintw (8, 29, _("Merry Christmas from the Snownews developers."));
mvaddstr (10, 29, _("Main code"));
@ -316,9 +319,9 @@ void xmasAbout (void) {
Snowfall(1);
}
/***************
* Santa Hunta *
***************/
//**************
// Santa Hunta
//*************
void SHDrawGun (int gun_pos) {
move (LINES-3, 0);
clrtoeol();
@ -419,9 +422,9 @@ void newSanta (santa * santa, int level) {
santa->height = 2;
santa->length = 27;
santa->gfx = "##___ __-+---+/*__-+---+/*";
santa->gfx_line2 = "_|__|_) /\\ /\\ /\\ /\\ "; /* Append 2 spaces! */
santa->gfx_line2 = "_|__|_) /\\ /\\ /\\ /\\ "; // Append 2 spaces!
santa->altgfx = "##___ __-+---+/*__-+---+/*";
santa->altgfx_line2 = "_|__|_) /| |\\ /| |\\ "; /* Append 1 space! */
santa->altgfx_line2 = "_|__|_) /| |\\ /| |\\ "; // Append 1 space!
}
int SHHit (shot shot, santa santa) {
@ -451,16 +454,16 @@ void SHDrawHitScore (scoreDisplay score) {
void printFinalScore (int score) {
int i, j, pos, number_count;
char *numbers[10][5] = {
{"_______","| _ |","| | | |","| |_| |","|_____|"}, /* 0 */
{" ____ "," / | ","/_/| | "," | | "," |_| "}, /* 1 */
{"_______","|___ |","| ____|","| |____","|_____|"}, /* 2 */
{"_______","|___ |"," ___ |","___| |","|_____|"}, /* 3 */
{"___ ___","| |_| |","|____ |"," | |"," |_|"}, /* 4 */
{"_______","| ___|","|___ |","____| |","|_____|"}, /* 5 */
{" __ "," / / "," / \\","| O /"," \\___/ "}, /* 6 */
{"_______","|___ |"," | |"," | |"," |_|"}, /* 7 */
{"_______","| _ |","| |_| |","| |_| |","|_____|"}, /* 8 */
{" ___ "," / \\ ","| O |"," \\ / "," \\__\\ "} /* 9 */
{"_______","| _ |","| | | |","| |_| |","|_____|"}, // 0
{" ____ "," / | ","/_/| | "," | | "," |_| "}, // 1
{"_______","|___ |","| ____|","| |____","|_____|"}, // 2
{"_______","|___ |"," ___ |","___| |","|_____|"}, // 3
{"___ ___","| |_| |","|____ |"," | |"," |_|"}, // 4
{"_______","| ___|","|___ |","____| |","|_____|"}, // 5
{" __ "," / / "," / \\","| O /"," \\___/ "}, // 6
{"_______","|___ |"," | |"," | |"," |_|"}, // 7
{"_______","| _ |","| |_| |","| |_| |","|_____|"}, // 8
{" ___ "," / \\ ","| O |"," \\ / "," \\__\\ "} // 9
};
int y;
int divisor;
@ -537,8 +540,8 @@ void santaHunta (void) {
scoreDisplay.rounds = 0;
/* Set ncurses halfdelay mode.
* Max resolution is 1/10sec */
// Set ncurses halfdelay mode.
// Max resolution is 1/10sec
halfdelay (1);
for (;;) {
@ -554,7 +557,7 @@ void santaHunta (void) {
targets = 1;
}
/* Pad drawing resolution to 1/10sec */
// Pad drawing resolution to 1/10sec
draw_delay += after.tv_usec - before.tv_usec;
if (draw_delay > 100000) {
draw_delay = 0;
@ -637,15 +640,14 @@ void santaHunta (void) {
refresh();
}
/* Leave halfdelay mode. */
// Leave halfdelay mode.
cbreak();
}
void UIAbout (void) {
int xpos;
clear(); /* Get the crap off the screen to make room
for our wonderful ASCII logo. :) */
clear();
xpos = COLS/2 - 40;
@ -658,8 +660,7 @@ void UIAbout (void) {
if (easterEgg()) {
santaHunta();
} else {
/* 80 COLS logo */
} else { // 80 COLS logo
mvaddstr (2, xpos, " ________ _______ ____ __________ _______ ______ __________ ________");
mvaddstr (3, xpos, " / _____/ \\ \\ / \\\\ | | \\\\ \\ / ___/ \\ | | \\ / ______/");
mvaddstr (4, xpos, " \\____ \\ \\ | \\ / /\\ \\\\ | / \\ | \\ / / \\ | / \\____ \\");

View File

@ -23,14 +23,14 @@
struct categories *first_category = NULL;
/* Compare global category list with string categoryname and return 1 if a
matching category was found. */
// Compare global category list with string categoryname and return 1 if a
// matching category was found.
int CategoryListItemExists (char * categoryname) {
struct categories *category;
for (category = first_category; category != NULL; category = category->next_ptr) {
if (strcasecmp (category->name, categoryname) == 0) {
/* Matching category found. */
// Matching category found.
return 1;
}
}
@ -39,8 +39,7 @@ int CategoryListItemExists (char * categoryname) {
}
/* The following functions add items to/delete items from the global
category list. */
// The following functions add items to/delete items from the global category list.
void CategoryListAddItem (char * categoryname) {
int inserted = 0;
struct categories *category;
@ -48,67 +47,67 @@ void CategoryListAddItem (char * categoryname) {
struct categories *new_ptr;
if (CategoryListItemExists (categoryname)) {
/* Only increase refcount */
// Only increase refcount
for (category = first_category; category != NULL; category = category->next_ptr) {
if (strcasecmp (category->name, categoryname) == 0)
category->refcount++;
}
} else {
/* Otherwise add item to structure */
// Otherwise add item to structure
category = malloc (sizeof(struct categories));
category->name = strdup (categoryname);
category->next_ptr = NULL;
if (first_category == NULL) {
/* Contains no elements */
// Contains no elements
category->next_ptr = first_category;
first_category = category;
} else {
for (new_ptr = first_category; new_ptr != NULL; new_ptr = new_ptr->next_ptr) {
if (strcasecmp (category->name, new_ptr->name) > 0) {
/* New category still below current one. Move on. */
// New category still below current one. Move on.
before_ptr = new_ptr;
} else {
if (before_ptr == NULL) {
/* Insert before first_ptr */
// Insert before first_ptr
category->next_ptr = first_category;
first_category = category;
} else {
/* Insert after first_ptr */
// Insert after first_ptr
before_ptr->next_ptr = category;
category->next_ptr = new_ptr;
}
inserted = 1;
/* Done with this loop. */
// Done with this loop.
break;
}
}
if (!inserted) {
/* No match from above. Insert new item at the end of the list. */
// No match from above. Insert new item at the end of the list.
before_ptr->next_ptr = category;
}
}
/* Set refcount to 1 for newly added category. */
// Set refcount to 1 for newly added category.
category->refcount = 1;
}
}
/* Delete item from category list. Decrease refcount for each deletion.
If refcount hits 0, remove from list. */
// Delete item from category list. Decrease refcount for each deletion.
// If refcount hits 0, remove from list.
void CategoryListDeleteItem (char * categoryname) {
struct categories *category;
struct categories *before_ptr = NULL; /* gcc complains ptr uninit with -O2 */
struct categories *before_ptr = NULL; // gcc complains ptr uninit with -O2
for (category = first_category; category != NULL; category = category->next_ptr) {
if (strcasecmp (category->name, categoryname) == 0) {
/* Check refcount */
// Check refcount
if (category->refcount > 1) {
/* Still at least one feed defining this category */
// Still at least one feed defining this category
category->refcount--;
break;
} else {
/* Last feed using this category removed, kill off the structure */
// Last feed using this category removed, kill off the structure
if (category == first_category) {
first_category = first_category->next_ptr;
free (category->name);
@ -126,8 +125,7 @@ void CategoryListDeleteItem (char * categoryname) {
}
}
/* The following two functions add items to/delete items from a feeds
category list. */
// The following two functions add items to/delete items from a feeds category list.
void FeedCategoryAdd (struct feed * cur_ptr, char * categoryname) {
int inserted = 0;
struct feedcategories *category;
@ -140,30 +138,30 @@ void FeedCategoryAdd (struct feed * cur_ptr, char * categoryname) {
if (cur_ptr->feedcategories == NULL) {
/* Contains no elements */
// Contains no elements
category->next_ptr = cur_ptr->feedcategories;
cur_ptr->feedcategories = category;
} else {
for (new_ptr = cur_ptr->feedcategories; new_ptr != NULL; new_ptr = new_ptr->next_ptr) {
if (strcasecmp (category->name, new_ptr->name) > 0) {
/* New category still below current one. Move on. */
// New category still below current one. Move on.
before_ptr = new_ptr;
} else {
if (before_ptr == NULL) {
category->next_ptr = cur_ptr->feedcategories;
cur_ptr->feedcategories = category;
} else {
/* The new category is now > current one. Insert it here. */
// The new category is now > current one. Insert it here.
before_ptr->next_ptr = category;
category->next_ptr = new_ptr;
}
inserted = 1;
/* Done with this loop. */
// Done with this loop.
break;
}
}
if (!inserted) {
/* No match from above. Insert new item at the end of the list. */
// No match from above. Insert new item at the end of the list.
before_ptr->next_ptr = category;
}
}
@ -176,7 +174,7 @@ void FeedCategoryDelete (struct feed * cur_ptr, char * categoryname) {
struct feedcategories *before_ptr = NULL;
char *tmpname;
/* categoryname == category->name which will be freed by this function! */
// categoryname == category->name which will be freed by this function!
tmpname = strdup (categoryname);
for (category = cur_ptr->feedcategories; category != NULL; category = category->next_ptr) {
@ -196,20 +194,20 @@ void FeedCategoryDelete (struct feed * cur_ptr, char * categoryname) {
before_ptr = category;
}
/* Decrease refcount in global category list. */
// Decrease refcount in global category list.
CategoryListDeleteItem (tmpname);
free (tmpname);
}
/* Compare a feeds category list with string categoryname and return 1 if a
matching category was found. */
// Compare a feeds category list with string categoryname and return 1 if a
// matching category was found.
int FeedCategoryExists (struct feed * cur_ptr, char * categoryname) {
struct feedcategories *category;
for (category = cur_ptr->feedcategories; category != NULL; category = category->next_ptr) {
if (strcasecmp (category->name, categoryname) == 0) {
/* Matching category found. */
// Matching category found.
return 1;
}
}
@ -217,13 +215,13 @@ int FeedCategoryExists (struct feed * cur_ptr, char * categoryname) {
return 0;
}
/* Set color label of category */
// Set color label of category
void CategoryListColors (char * categoryname, char * label) {
struct categories *category;
for (category = first_category; category != NULL; category = category->next_ptr) {
if (strcasecmp (category->name, categoryname) == 0) {
/* Matching category found. */
// Matching category found.
if (strlen(label) > 5) {
category->label = atoi (label+5);
if ((category->label == 12) ||
@ -236,13 +234,13 @@ void CategoryListColors (char * categoryname, char * label) {
}
}
/* Return color label number and bold status of given category */
// Return color label number and bold status of given category
int CategoryGetLabel (char * categoryname, int type) {
struct categories *category;
for (category = first_category; category != NULL; category = category->next_ptr) {
if (strcasecmp (category->name, categoryname) == 0) {
/* Matching category found. */
// Matching category found.
if (type == 0)
return category->label;
else
@ -252,12 +250,10 @@ int CategoryGetLabel (char * categoryname, int type) {
return -1;
}
/*
* Return a comma-separated list of categories defined for the provided feed,
* NULL if no category is defined for the feed.
*
* The caller must free the list.
*/
// Return a comma-separated list of categories defined for the provided feed,
// NULL if no category is defined for the feed.
//
// The caller must free the list.
char *GetCategoryList (struct feed *feed) {
struct feedcategories *category;
char *categories = NULL;
@ -279,9 +275,7 @@ char *GetCategoryList (struct feed *feed) {
return categories;
}
/*
* Free and reset the filters list.
*/
// Free and reset the filters list.
void ResetFilters (char **filters) {
int i;

View File

@ -23,17 +23,17 @@ int FeedCategoryExists (struct feed * cur_ptr, char * categoryname);
char *GetCategoryList (struct feed * feed);
void ResetFilters (char **filters);
/* A feeds categories */
// A feeds categories
struct feedcategories {
char * name; /* Category name */
char* name; // Category name
struct feedcategories * next_ptr;
};
/* Global list of all defined categories, their refcounts and color labels. */
// Global list of all defined categories, their refcounts and color labels.
struct categories {
char * name; /* Category name */
int refcount; /* Number of feeds using this category. */
int label; /* Color label of this category. */
char* name; // Category name
int refcount; // Number of feeds using this category.
int label; // Color label of this category.
int labelbold;
struct categories * next_ptr;
};

View File

@ -17,64 +17,64 @@
#ifndef CONFIG_H
#define CONFIG_H
/* Define to the one symbol short name of this package */
// Define to the one symbol short name of this package
#define @PKG_UNAME@_NAME "@PKG_NAME@"
/* Define to the version of this package */
// Define to the version of this package
#define @PKG_UNAME@_VERSION @PKG_VERSION@
/* Define to the version string of this package */
// Define to the version string of this package
#define @PKG_UNAME@_VERSTRING "@PKG_VERSTR@"
/* Define to the address where bug reports for this package should be sent */
// Define to the address where bug reports for this package should be sent
#define @PKG_UNAME@_BUGREPORT "@PKG_BUGREPORT@"
/* Define to the value of LOCALEPATH environment variable */
// Define to the value of LOCALEPATH environment variable
#define LOCALEPATH "@localedir@"
/* Define to use experimental code */
// Define to use experimental code
#undef USE_UNSUPPORTED_AND_BROKEN_CODE
/* Define to output of uname */
// Define to output of uname
#undef OS
/* Define on SunOS and Solaris */
// Define on SunOS and Solaris
#undef SUN
#include "version.h"
#include "netio.h"
struct feed {
char *feedurl; /* Non hashified URL */
char *feed; /* Raw XML */
char *feedurl; // Non hashified URL
char *feed; // Raw XML
int content_length;
char *title;
char *link;
char *description;
char *lastmodified; /* Content of header as sent by the server. */
char *lastmodified; // Content of header as sent by the server.
int lasthttpstatus;
char *content_type;
netio_error_type netio_error; /* See netio.h */
int connectresult; /* Socket errno */
char *cookies; /* Login cookies for this feed. */
char *authinfo; /* HTTP authinfo string. */
char *servauth; /* Server supplied authorization header. */
netio_error_type netio_error; // See netio.h
int connectresult; // Socket errno
char *cookies; // Login cookies for this feed.
char *authinfo; // HTTP authinfo string.
char *servauth; // Server supplied authorization header.
struct newsitem * items;
struct feed *next_ptr, *prev_ptr;
int problem; /* Set if there was a problem downloading the feed. */
char *override; /* Custom feed title. */
char *original; /* Original feed title. */
char *perfeedfilter; /* Pipe feed through this program before parsing. */
int execurl; /* Execurl? */
int smartfeed; /* 1: new items feed. */
int problem; // Set if there was a problem downloading the feed.
char *override; // Custom feed title.
char *original; // Original feed title.
char *perfeedfilter; // Pipe feed through this program before parsing.
int execurl; // Execurl?
int smartfeed; // 1: new items feed.
struct feedcategories * feedcategories;
};
struct newsitem {
struct newsdata *data;
struct newsitem *next_ptr, *prev_ptr; /* Pointer to next/prev item in double linked list */
struct newsitem *next_ptr, *prev_ptr; // Pointer to next/prev item in double linked list
};
struct newsdata {
struct feed *parent;
int readstatus; /* 0: unread, 1: read */
int readstatus; // 0: unread, 1: read
char *title;
char *link;
char *description;
@ -82,7 +82,7 @@ struct newsdata {
int date;
};
/* Global program keybindings. Loaded from setup:Config() */
// Global program keybindings. Loaded from setup:Config()
struct keybindings {
char next;
char prev;
@ -121,7 +121,7 @@ struct keybindings {
char typeahead;
};
/* Color definitions */
// Color definitions
struct color {
int newitems;
int newitemsbold;
@ -134,19 +134,19 @@ struct color {
extern struct feed *first_ptr;
#ifdef LOCALEPATH
# include <libintl.h>
# include <locale.h>
#include <libintl.h>
#include <locale.h>
#endif
#ifdef LOCALEPATH
# define _(String) gettext (String)
#define _(String) gettext (String)
#else
# define _(String) (String)
# define ngettext(Singular, Plural, n) (Plural)
#define _(String) (String)
#define ngettext(Singular, Plural, n) (Plural)
#endif
#ifdef SUN
# include "os-support.h"
#include "os-support.h"
#endif
#endif

View File

@ -16,7 +16,7 @@
// along with Snownews. If not, see http://www.gnu.org/licenses/.
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <sys/types.h>
#include <string.h>
@ -51,26 +51,26 @@ char * iconvert (const char * inbuf) {
#else
char * iconvert (char * inbuf) {
#endif
iconv_t cd; /* Iconvs conversion descriptor. */
char *outbuf, *outbuf_first; /* We need two pointers so we do not lose
the string starting position. */
iconv_t cd; // Iconvs conversion descriptor.
char *outbuf, *outbuf_first; // We need two pointers so we do not lose
// the string starting position.
char target_charset[64];
size_t inbytesleft, outbytesleft;
/*(void)strlcpy(target_charset, nl_langinfo(CODESET), sizeof(target_charset));*/
//(void)strlcpy(target_charset, nl_langinfo(CODESET), sizeof(target_charset));
strncpy(target_charset, nl_langinfo(CODESET), sizeof(target_charset));
/* Take a shortcut. */
// Take a shortcut.
if (strcasecmp (target_charset, "UTF-8") == 0)
return strdup(inbuf);
inbytesleft = strlen(inbuf);
outbytesleft = strlen(inbuf);
/*(void)strlcat(target_charset, "//TRANSLIT", sizeof(target_charset));*/
//(void)strlcat(target_charset, "//TRANSLIT", sizeof(target_charset));
strncat(target_charset, "//TRANSLIT", sizeof(target_charset));
/* cd = iconv_open(nl_langinfo(CODESET), "UTF-8"); */
// cd = iconv_open(nl_langinfo(CODESET), "UTF-8");
if (forced_target_charset) {
cd = iconv_open (forced_target_charset, "UTF-8");
} else {
@ -97,44 +97,43 @@ char * iconvert (char * inbuf) {
}
/* UIDejunk: remove crap (=html tags) from feed description and convert
* html entities to something useful if we hit them.
* This function took almost forever to get right, but at least I learned
* that html entity &hellip; has nothing to do with Lucifer's ISP, but
* instead means "..." (3 dots, "and so on...").
*/
// UIDejunk: remove html tags from feed description and convert
// html entities to something useful if we hit them.
// This function took almost forever to get right, but at least I learned
// that html entity &hellip; has nothing to do with Lucifer's ISP, but
// instead means "..." (3 dots, "and so on...").
char * UIDejunk (char * feed_description) {
char *start; /* Points to first char everytime. Need to free this. */
char *text; /* feed_description copy */
char *newtext; /* Detag'ed *text. */
char *detagged; /* Returned value from strsep. This is what we want. */
char *start; // Points to first char everytime. Need to free this.
char *text; // feed_description copy
char *newtext; // Detag'ed *text.
char *detagged; // Returned value from strsep. This is what we want.
char *htmltag;
/* char *attribute;*/
// char *attribute;
char *entity;
struct entity *cur_entity;
int found = 0; /* User defined entity matched? */
/* int len;*/
int found = 0; // User defined entity matched?
// int len;
#ifdef __STDC_ISO_10646__
int len;
wchar_t ch; /* Decoded numeric entity */
int mblen; /* Length of multi-byte entity */
wchar_t ch; // Decoded numeric entity
int mblen; // Length of multi-byte entity
#else
unsigned long ch; /* Decoded numeric entity */
unsigned long ch; // Decoded numeric entity
#endif
const htmlEntityDesc *ep; /* For looking up HTML entities */
const htmlEntityDesc *ep; // For looking up HTML entities
/* Gracefully handle passed NULL ptr. */
// Gracefully handle passed NULL ptr.
if (feed_description == NULL) {
newtext = strdup("(null)");
return newtext;
}
/* Make a copy and point *start to it so we can free the stuff again! */
// Make a copy and point *start to it so we can free the stuff again!
text = strdup (feed_description);
start = text;
/* If text begins with a tag, discard all of them. */
// If text begins with a tag, discard all of them.
while (1) {
if (text[0] == '<') {
strsep (&text, "<");
@ -151,14 +150,14 @@ char * UIDejunk (char * feed_description) {
newtext[0] = '\0';
while (1) {
/* Strip tags... tagsoup mode. */
/* strsep puts everything before "<" into detagged. */
// Strip tags... tagsoup mode.
// strsep puts everything before "<" into detagged.
detagged = strsep (&text, "<");
if (detagged == NULL)
break;
/* Replace <p> and <br> (in all incarnations) with newlines, but only
if there isn't already a following newline. */
// Replace <p> and <br> (in all incarnations) with newlines, but only
// if there isn't already a following newline.
if (text != NULL) {
if ((strncasecmp (text, "p", 1) == 0) ||
(strncasecmp (text, "br", 2) == 0)) {
@ -173,40 +172,43 @@ char * UIDejunk (char * feed_description) {
}
newtext = realloc (newtext, strlen(newtext)+strlen(detagged)+1);
/* Now append detagged to newtext. */
// Now append detagged to newtext.
strcat (newtext, detagged);
/* Advance *text to next position after the closed tag. */
// Advance *text to next position after the closed tag.
htmltag = strsep (&text, ">");
if (htmltag == NULL)
break;
if (s_strcasestr(htmltag, "img src") != NULL) {
/* attribute = s_strcasestr(htmltag, "alt=");
#if 0
attribute = s_strcasestr(htmltag, "alt=");
if (attribute == NULL)
continue;
len = strlen(attribute);
newtext = realloc(newtext, strlen(newtext)+6+len+2);
strcat(newtext, "[img: ");
strncat(newtext, attribute+5, len-6);
strcat(newtext, "]");*/
strcat(newtext, "]");
#endif
newtext = realloc(newtext, strlen(newtext)+7);
strcat(newtext, "[img] ");
}
/* else if (s_strcasestr(htmltag, "a href") != NULL) {
#if 0
else if (s_strcasestr(htmltag, "a href") != NULL) {
newtext = realloc(newtext, strlen(newtext)+8);
strcat(newtext, "[link: ");
} else if (strcasecmp(htmltag, "/a") == 0) {
newtext = realloc(newtext, strlen(newtext)+2);
strcat(newtext, "]");
}*/
}
#endif
}
free (start);
CleanupString (newtext, 0);
/* See if there are any entities in the string at all. */
// See if there are any entities in the string at all.
if (strchr(newtext, '&') != NULL) {
text = strdup (newtext);
start = text;
@ -216,7 +218,7 @@ char * UIDejunk (char * feed_description) {
newtext[0] = '\0';
while (1) {
/* Strip HTML entities. */
// Strip HTML entities.
detagged = strsep (&text, "&");
if (detagged == NULL)
break;
@ -225,12 +227,12 @@ char * UIDejunk (char * feed_description) {
newtext = realloc (newtext, strlen(newtext)+strlen(detagged)+1);
strcat (newtext, detagged);
}
/* Expand newtext by one char. */
// Expand newtext by one char.
newtext = realloc (newtext, strlen(newtext)+2);
/* This might break if there is an & sign in the text. */
// This might break if there is an & sign in the text.
entity = strsep (&text, ";");
if (entity != NULL) {
/* XML defined entities. */
// XML defined entities.
if (strcmp(entity, "amp") == 0) {
strcat (newtext, "&");
continue;
@ -248,31 +250,31 @@ char * UIDejunk (char * feed_description) {
continue;
}
/* Decode user defined entities. */
// Decode user defined entities.
found = 0;
for (cur_entity = first_entity; cur_entity != NULL; cur_entity = cur_entity->next_ptr) {
if (strcmp (entity, cur_entity->entity) == 0) {
/* We have found a matching entity. */
// We have found a matching entity.
/* If entity_length is more than 1 char we need to realloc
more space in newtext. */
// If entity_length is more than 1 char we need to realloc
// more space in newtext.
if (cur_entity->entity_length > 1)
newtext = realloc (newtext, strlen(newtext)+cur_entity->entity_length+1);
/* Append new entity. */
// Append new entity.
strcat (newtext, cur_entity->converted_entity);
/* Set found flag. */
// Set found flag.
found = 1;
/* We can now leave the for loop. */
// We can now leave the for loop.
break;
}
}
/* Try to parse some standard entities. */
// Try to parse some standard entities.
if (!found) {
/* See if it was a numeric entity. */
// See if it was a numeric entity.
if (entity[0] == '#') {
if (entity[1] == 'x')
ch = strtoul(entity + 2, NULL, 16);
@ -282,21 +284,21 @@ char * UIDejunk (char * feed_description) {
else if ((ep = htmlEntityLookup((xmlChar *)entity)) != NULL)
ch = ep->value;
else
ch = 0; /* Didn't recognize it. */
ch = 0; // Didn't recognize it.
if (ch > 0) {
#ifdef __STDC_ISO_10646__
/* Convert to locale encoding and append. */
// Convert to locale encoding and append.
len = strlen(newtext);
newtext = realloc(newtext, len + MB_CUR_MAX + 1);
mblen = wctomb(newtext + len, ch);
/* Only set found flag if the conversion worked. */
// Only set found flag if the conversion worked.
if (mblen > 0) {
newtext[len + mblen] = '\0';
found = 1;
}
#else
/* Since we can't use wctomb(), just convert ASCII. */
// Since we can't use wctomb(), just convert ASCII.
if (ch <= 0x7F) {
sprintf(newtext + strlen(newtext), "%c", (int)ch);
found = 1;
@ -305,10 +307,10 @@ char * UIDejunk (char * feed_description) {
}
}
/* If nothing matched so far, put text back in. */
// If nothing matched so far, put text back in.
if (!found) {
/* Changed into &+entity to avoid stray semicolons
at the end of wrapped text if no entity matches. */
// Changed into &+entity to avoid stray semicolons
// at the end of wrapped text if no entity matches.
newtext = realloc (newtext, strlen(newtext)+strlen(entity)+2);
strcat (newtext, "&");
strcat (newtext, entity);
@ -321,24 +323,19 @@ char * UIDejunk (char * feed_description) {
return newtext;
}
/* 5th try at a wrap text functions.
* My first version was broken, my second one sucked, my third try was
* so overcomplicated I didn't understand it anymore... Kianga tried
* the 4th version which corrupted some random memory unfortunately...
* but this one works. Heureka!
*/
// 5th try at a wrap text functions.
// My first version was broken, my second one sucked, my third try was
// so overcomplicated I didn't understand it anymore... Kianga tried
// the 4th version which corrupted some random memory unfortunately...
// but this one works. Heureka!
char* WrapText (const char* text, unsigned width) {
char *newtext;
char *textblob; /* Working copy of text. */
char *textblob; // Working copy of text.
char *chapter;
char *line; /* One line of text with max width. */
char *savepos; /* Saved position pointer so we can go back in the string. */
char *line; // One line of text with max width.
char *savepos; // Saved position pointer so we can go back in the string.
char *chunk;
char *start;
/*
char *p;
int lena, lenb;
*/
textblob = strdup (text);
start = textblob;
@ -351,7 +348,7 @@ char* WrapText (const char* text, unsigned width) {
memset (newtext, 0, 1);
while (1) {
/* First, cut at \n. */
// First, cut at \n.
chapter = strsep (&textblob, "\n");
if (chapter == NULL)
break;
@ -359,35 +356,33 @@ char* WrapText (const char* text, unsigned width) {
savepos = chapter;
chunk = strsep (&chapter, " ");
/* Last chunk. */
// Last chunk.
if (chunk == NULL) {
if (line != NULL) {
newtext = realloc (newtext, strlen(newtext)+strlen(line)+2);
strcat (newtext, line);
strcat (newtext, "\n");
/* Faster replacement with memcpy.
* Overkill, overcomplicated and smelling of bugs all over.
*/
/*
lena = strlen(newtext);
lenb = strlen(line);
newtext = realloc (newtext, lena+lenb+2);
p = newtext+lena;
memcpy (p, line, lenb);
p += lenb;
*p = '\n';
p++;
*p=0;
*/
// Faster replacement with memcpy.
// Overkill, overcomplicated and smelling of bugs all over.
#if 0
lena = strlen(newtext);
lenb = strlen(line);
newtext = realloc (newtext, lena+lenb+2);
p = newtext+lena;
memcpy (p, line, lenb);
p += lenb;
*p = '\n';
p++;
*p=0;
#endif
line[0] = '\0';
}
break;
}
if (strlen(chunk) > width) {
/* First copy remaining stuff in line to newtext. */
// First copy remaining stuff in line to newtext.
newtext = realloc (newtext, strlen(newtext)+strlen(line)+2);
strcat (newtext, line);
strcat (newtext, "\n");
@ -396,7 +391,7 @@ char* WrapText (const char* text, unsigned width) {
line = malloc (1);
line[0] = '\0';
/* Then copy chunk with max length of line to newtext. */
// Then copy chunk with max length of line to newtext.
line = realloc (line, width+1);
strncat (line, chunk, width-5);
strcat (line, "...");
@ -414,7 +409,7 @@ char* WrapText (const char* text, unsigned width) {
strcat (line, chunk);
strcat (line, " ");
} else {
/* Why the fuck can chapter be NULL here anyway? */
// Why can chapter be NULL here anyway?
if (chapter != NULL) {
chapter--;
chapter[0] = ' ';
@ -493,28 +488,28 @@ char *base64encode(char const *inbuf, unsigned int inbuf_size) {
}
#ifdef USE_UNSUPPORTED_AND_BROKEN_CODE
/* Returns NULL on invalid input */
// Returns NULL on invalid input
char* decodechunked(char * chunked, unsigned int *inputlen) {
#warning ===The function decodedechunked() is not safe for binary data. Since you specifically requested it to be compiled in you probably know better what you are doing than me. Do not report bugs for this code.===
char *orig = chunked, *dest = chunked;
unsigned long chunklen;
/* We can reuse the same buffer to dechunkify it:
* the data size will never increase. */
// We can reuse the same buffer to dechunkify it:
// the data size will never increase.
while((chunklen = strtoul(orig, &orig, 16))) {
/* process one more chunk: */
/* skip chunk-extension part */
// process one more chunk:
// skip chunk-extension part
while(*orig && (*orig != '\r'))
orig++;
/* skip '\r\n' after chunk length */
// skip '\r\n' after chunk length
orig += 2;
if(( chunklen > (chunked + *inputlen - orig)))
/* insane chunk length. Well... */
// insane chunk length. Well...
return NULL;
memmove(dest, orig, chunklen);
dest += chunklen;
orig += chunklen;
/* and go to the next chunk */
// and go to the next chunk
}
*dest = '\0';
*inputlen = dest - chunked;
@ -523,15 +518,14 @@ char* decodechunked(char * chunked, unsigned int *inputlen) {
}
#endif
/* Remove leading whitspaces, newlines, tabs.
* This function should be safe for working on UTF-8 strings.
* tidyness: 0 = only suck chars from beginning of string
* 1 = extreme, vacuum everything along the string.
*/
// Remove leading whitspaces, newlines, tabs.
// This function should be safe for working on UTF-8 strings.
// tidyness: 0 = only suck chars from beginning of string
// 1 = extreme, vacuum everything along the string.
void CleanupString (char * string, int tidyness) {
int len, i;
/* If we are passed a NULL pointer, leave it alone and return. */
// If we are passed a NULL pointer, leave it alone and return.
if (string == NULL)
return;
@ -539,21 +533,21 @@ void CleanupString (char * string, int tidyness) {
while ((string[0] == '\n' || string [0] == ' ' || string [0] == '\t') &&
(len > 0)) {
/* len=strlen(string) does not include \0 of string.
But since we copy from *string+1 \0 gets included.
Delicate code. Think twice before it ends in buffer overflows. */
// len=strlen(string) does not include \0 of string.
// But since we copy from *string+1 \0 gets included.
// Delicate code. Think twice before it ends in buffer overflows.
memmove (string, string+1, len);
len--;
}
/* Remove trailing spaces. */
// Remove trailing spaces.
while ((len > 1) && (string[len-1] == ' ')) {
string[len-1] = 0;
len--;
}
len = strlen(string);
/* Eat newlines and tabs along the whole string. */
// Eat newlines and tabs along the whole string.
for (i = 0; i < len; i++) {
if (string[i] == '\t') {
string[i] = ' ';
@ -564,7 +558,7 @@ void CleanupString (char * string, int tidyness) {
}
}
/* http://foo.bar/address.rdf -> http:__foo.bar_address.rdf */
// http://foo.bar/address.rdf -> http:__foo.bar_address.rdf
char * Hashify (const char * url) {
int i, len;
char *hashed_url;
@ -573,9 +567,7 @@ char * Hashify (const char * url) {
len = strlen(hashed_url);
/* Don't allow filenames > 128 chars for teeny weeny
* operating systems.
*/
// Don't allow filenames > 128 chars for teeny weeny operating systems.
if (len > 128) {
len = 128;
hashed_url[128] = '\0';
@ -589,8 +581,7 @@ char * Hashify (const char * url) {
(hashed_url[i] != 0))
hashed_url[i] = '_';
/* Cygwin doesn't seem to like anything besides a-z0-9 in filenames.
Zap'em! */
// Cygwin doesn't seem to like anything besides a-z0-9 in filenames. Zap'em!
#ifdef __CYGWIN__
if (((hashed_url[i] < 48) || (hashed_url[i] > 57)) &&
((hashed_url[i] < 65) || (hashed_url[i] > 90)) &&
@ -622,22 +613,22 @@ char * genItemHash (const char* const* hashitems, int items) {
return strdup(md5_hex);
}
/* Date conversion */
/* 2004-11-20T19:45:00+00:00 */
// Date conversion
// 2004-11-20T19:45:00+00:00
int ISODateToUnix (char const * const ISODate) {
struct tm *t;
time_t tt = 0;
int time_unix = 0;
/* Do not crash with an empty tag */
// Do not crash with an empty tag
if (ISODate == NULL)
return 0;
t = malloc(sizeof(struct tm));
gmtime_r(&tt, t);
/* OpenBSD does not know %F == %Y-%m-%d
* <insert inflamatory comment here> */
// OpenBSD does not know %F == %Y-%m-%d
// <insert inflamatory comment here>
if (strptime(ISODate, "%Y-%m-%dT%T", t)) {
#ifdef __CYGWIN__
time_unix = mktime(t);
@ -655,14 +646,14 @@ int ISODateToUnix (char const * const ISODate) {
free (t);
return time_unix;
}
/* Sat, 20 Nov 2004 21:45:40 +0000 */
// Sat, 20 Nov 2004 21:45:40 +0000
int pubDateToUnix (char const * const pubDate) {
char const *start_here;
struct tm *t;
time_t tt = 0;
int time_unix = 0;
/* Do not crash with an empty Tag */
// Do not crash with an empty Tag
if (pubDate == NULL)
return 0;
@ -673,19 +664,17 @@ int pubDateToUnix (char const * const pubDate) {
gmtime_r(&tt, t);
#ifdef LOCALEPATH
/* Cruft!
* Save old locale so we can parse the stupid pubDate format.
* However strftime is not really more intelligent since there is no
* format string for abbr. month name NOT in the current locale. Grr.
*
* This is also not thread safe!
*/
// Cruft!
// Save old locale so we can parse the stupid pubDate format.
// However strftime is not really more intelligent since there is no
// format string for abbr. month name NOT in the current locale. Grr.
//
// This is also not thread safe!
char* oldlocale = strdup(setlocale(LC_TIME, NULL));
if (oldlocale) {
/* Only reset if setlocale returned something !NULL.
* Will not parse the date correctly in this case, but will also not
* overwrite the user's locale setting.
*/
// Only reset if setlocale returned something !NULL.
// Will not parse the date correctly in this case, but will also not
// overwrite the user's locale setting.
setlocale(LC_TIME, "C");
}
#endif
@ -786,6 +775,6 @@ static int calcAgeInDays (const struct tm* t) {
struct tm current_t;
gmtime_r(&unix_t, &current_t);
/* (((current year - passed year) * 365) + current year day) - passed year day */
// (((current year - passed year) * 365) + current year day) - passed year day
return (((current_t.tm_year - t->tm_year) * 365) + current_t.tm_yday) - t->tm_yday;
}

View File

@ -14,11 +14,10 @@
// You should have received a copy of the GNU General Public License
// along with Snownews. If not, see http://www.gnu.org/licenses/.
/* Netscape cookie file format:
(http://www.cookiecentral.com/faq/#3.5)
.host.com host_match[BOOL] /path secure[BOOL] expire[unix time] NAME VALUE
*/
// Netscape cookie file format:
// (http://www.cookiecentral.com/faq/#3.5)
//
// .host.com host_match[BOOL] /path secure[BOOL] expire[unix time] NAME VALUE
#include <string.h>
#include <stdio.h>
@ -29,10 +28,10 @@
#include "ui-support.h"
void CookieCutter (struct feed * cur_ptr, FILE * cookies) {
char buf[4096]; /* File read buffer. */
char buf[4096]; // File read buffer.
char tmp[512];
char *host; /* Current feed hostname. */
char *path; /* Current feed path. */
char *host; // Current feed hostname.
char *path; // Current feed path.
char *url;
char *freeme, *tmpstr;
char *tmphost;
@ -48,7 +47,7 @@ void CookieCutter (struct feed * cur_ptr, FILE * cookies) {
int cookienr = 0;
time_t tunix;
/* Get current time. */
// Get current time.
tunix = time(0);
url = strdup (cur_ptr->feedurl);
@ -63,7 +62,7 @@ void CookieCutter (struct feed * cur_ptr, FILE * cookies) {
return;
}
/* If tmphost contains an '@' strip authinfo off url. */
// If tmphost contains an '@' strip authinfo off url.
if (strchr (tmphost, '@') != NULL) {
strsep (&tmphost, "@");
}
@ -83,23 +82,23 @@ void CookieCutter (struct feed * cur_ptr, FILE * cookies) {
if ((fgets (buf, sizeof(buf), cookies)) == NULL)
break;
/* Filter \n lines. But ignore them so we can read a NS cookie file. */
// Filter \n lines. But ignore them so we can read a NS cookie file.
if (buf[0] == '\n')
continue;
/* Allow adding of comments that start with '#'.
Makes it possible to symlink Mozilla's cookies.txt. */
// Allow adding of comments that start with '#'.
// Makes it possible to symlink Mozilla's cookies.txt.
if (buf[0] == '#')
continue;
cookie = strdup (buf);
freeme = cookie;
/* Munch trailing newline. */
// Munch trailing newline.
if (cookie[strlen(cookie)-1] == '\n')
cookie[strlen(cookie)-1] = '\0';
/* Decode the cookie string. */
// Decode the cookie string.
for (i = 0; i <= 6; i++) {
tmpstr = strsep (&cookie, "\t");
@ -108,31 +107,31 @@ void CookieCutter (struct feed * cur_ptr, FILE * cookies) {
switch (i) {
case 0:
/* Cookie hostname. */
// Cookie hostname.
cookiehost = strdup (tmpstr);
break;
case 1:
/* Discard host match value. */
// Discard host match value.
break;
case 2:
/* Cookie path. */
// Cookie path.
cookiepath = strdup (tmpstr);
break;
case 3:
/* Secure cookie? */
// Secure cookie?
if (strcasecmp (tmpstr, "TRUE") == 0)
cookiesecure = 1;
break;
case 4:
/* Cookie expiration date. */
// Cookie expiration date.
cookieexpire = atoi (tmpstr);
break;
case 5:
/* NAME */
// NAME
cookiename = strdup (tmpstr);
break;
case 6:
/* VALUE */
// VALUE
cookievalue = strdup (tmpstr);
break;
default:
@ -140,19 +139,19 @@ void CookieCutter (struct feed * cur_ptr, FILE * cookies) {
}
}
/* See if current cookie matches cur_ptr.
Hostname and path must match.
Ignore secure cookies.
Discard cookie if it has expired. */
// See if current cookie matches cur_ptr.
// Hostname and path must match.
// Ignore secure cookies.
// Discard cookie if it has expired.
if ((strstr (host, cookiehost) != NULL) &&
(strstr (path, cookiepath) != NULL) &&
(!cookiesecure) &&
(cookieexpire > (int) tunix)) { /* Cast time_t tunix to int. */
(cookieexpire > (int) tunix)) { // Cast time_t tunix to int.
cookienr++;
/* Construct and append cookiestring.
Cookie: NAME=VALUE; NAME=VALUE */
// Construct and append cookiestring.
//
// Cookie: NAME=VALUE; NAME=VALUE
if (cookienr == 1) {
len = 8 + strlen(cookiename) + 1 + strlen(cookievalue) + 1;
cur_ptr->cookies = malloc (len);
@ -170,8 +169,8 @@ void CookieCutter (struct feed * cur_ptr, FILE * cookies) {
}
} else if ((strstr (host, cookiehost) != NULL) &&
(strstr (path, cookiepath) != NULL) &&
(cookieexpire < (int) tunix)) { /* Cast time_t tunix to int. */
/* Print cookie expire warning. */
(cookieexpire < (int) tunix)) { // Cast time_t tunix to int.
// Print cookie expire warning.
snprintf (tmp, sizeof(tmp), _("Cookie for %s has expired!"), cookiehost);
UIStatus (tmp, 1, 1);
}
@ -188,7 +187,7 @@ void CookieCutter (struct feed * cur_ptr, FILE * cookies) {
free (path);
free (freeme);
/* Append \r\n to cur_ptr->cookies */
// Append \r\n to cur_ptr->cookies
if (cur_ptr->cookies != NULL) {
cur_ptr->cookies = realloc (cur_ptr->cookies, len+2);
strcat (cur_ptr->cookies, "\r\n");
@ -199,13 +198,12 @@ void CookieCutter (struct feed * cur_ptr, FILE * cookies) {
void LoadCookies (struct feed * cur_ptr) {
char file[512]; /* File locations. */
FILE *cookies; /* Cookies file ptr. */
char file[512]; // File locations.
FILE *cookies; // Cookies file ptr.
snprintf (file, sizeof(file), "%s/.snownews/cookies", getenv("HOME"));
cookies = fopen (file, "r");
if (cookies == NULL) {
/* No cookies to load. */
if (cookies == NULL) { // No cookies to load.
return;
} else {
CookieCutter (cur_ptr, cookies);

176
dialog.c
View File

@ -45,15 +45,15 @@ char * UIOneLineEntryField (int x, int y) {
text = malloc(512);
/* UIStatus switches off attron! */
// UIStatus switches off attron!
attron (WA_REVERSE);
echo();
curs_set(1);
move (y, x);
/* Beware of hardcoded textlength size!
getnstr size does NOT include \0. This is really stupid and causes
1-byte overflows. Always size=len-1! */
// Beware of hardcoded textlength size!
// getnstr size does NOT include \0. This is really stupid and causes
// 1-byte overflows. Always size=len-1!
getnstr (text, 511);
noecho();
@ -61,7 +61,7 @@ char * UIOneLineEntryField (int x, int y) {
curs_set(0);
attroff (WA_REVERSE);
/* This memory needs to be freed in the calling function! */
// This memory needs to be freed in the calling function!
return text;
}
@ -72,14 +72,14 @@ void UIChangeBrowser (void) {
repeat:
/* malloc = 17 (strlen("Current setting: ") + browser
We will malloc a bigger junk, because other languages
might need longer strings and crash! */
// malloc = 17 (strlen("Current setting: ") + browser
// We will malloc a bigger junk, because other languages
// might need longer strings and crash!
len = strlen(_("Current setting: %s")) + strlen(browser) + 1;
browserstring = malloc (len);
snprintf (browserstring, len, _("Current setting: %s"), browser);
/* Clear screen area we want to "draw" to. */
// Clear screen area we want to "draw" to.
attron (WA_REVERSE);
UISupportDrawBox (3, 5, COLS-4, 7);
@ -110,15 +110,14 @@ void UIChangeBrowser (void) {
free (browserstring);
}
/* Dialog to change feedname.
Return: 0 on success
1 on user abort
2 original title restored
*/
// Dialog to change feedname.
// Return: 0 on success
// 1 on user abort
// 2 original title restored
void UIChangeFeedName (struct feed *cur_ptr) {
char *newname;
/* Clear screen area we want to "draw" to. */
// Clear screen area we want to "draw" to.
attron (WA_REVERSE);
UISupportDrawBox (3, 5, COLS-4, 7);
@ -126,27 +125,27 @@ void UIChangeFeedName (struct feed *cur_ptr) {
newname = UIOneLineEntryField (5, 6);
/* If strlen is zero, return 1. */
// If strlen is zero, return 1.
if (strlen(newname) == 0) {
free (newname);
return;
}
/* If newname contains "|", abort since this is used as a delimiter for the config file. */
// If newname contains "|", abort since this is used as a delimiter for the config file.
if (strstr (newname, "|") != NULL) {
free (newname);
UIStatus (_("The new title must not contain a \"|\" character!"), 2, 0);
return ;
}
/* Restor original title. */
// Restor original title.
if ((newname != NULL) && (cur_ptr->override != NULL)) {
if (strcmp(newname, "-") == 0) {
if (cur_ptr->title != NULL)
free (cur_ptr->title);
cur_ptr->title = strdup(cur_ptr->original);
free (cur_ptr->original);
/* Set back original to NULL pointer. */
// Set back original to NULL pointer.
cur_ptr->original = NULL;
free (cur_ptr->override);
cur_ptr->override = NULL;
@ -155,15 +154,15 @@ void UIChangeFeedName (struct feed *cur_ptr) {
}
}
/* Copy new name into ->override. */
// Copy new name into ->override.
free (cur_ptr->override);
cur_ptr->override = strdup (newname);
/* Save original. */
// Save original.
free (cur_ptr->original);
cur_ptr->original = strdup (cur_ptr->title);
/* Set new title. */
// Set new title.
free (cur_ptr->title);
cur_ptr->title = strdup (newname);
@ -171,15 +170,15 @@ void UIChangeFeedName (struct feed *cur_ptr) {
return;
}
/* Popup window to add new RSS feed. Passing an URL will
automatically add it, no questions asked. */
// Popup window to add new RSS feed. Passing an URL will
// automatically add it, no questions asked.
int UIAddFeed (char * newurl) {
char tmp[512];
char *url;
struct feed *new_ptr;
if (newurl == NULL) {
/* Clear screen area we want to "draw" to. */
// Clear screen area we want to "draw" to.
attron (WA_REVERSE);
UISupportDrawBox (3, 5, COLS-4, 7);
@ -187,8 +186,8 @@ int UIAddFeed (char * newurl) {
url = UIOneLineEntryField (5, 6);
/* If read stringlength is ZARO (abort of action requested) return 1
and confuse the calling function. */
// If read stringlength is ZARO (abort of action requested) return 1
// and confuse the calling function.
if (strlen(url) == 0) {
free (url);
return 1;
@ -196,13 +195,13 @@ int UIAddFeed (char * newurl) {
CleanupString(url, 0);
/* Support that stupid feed:// "protocol" */
// Support that stupid feed:// "protocol"
if (strncasecmp (url, "feed://", 7) == 0)
memcpy (url, "http", 4);
/* If URL does not start with the procotol specification,
assume http://
-> tmp[512] -> we can "only" use max 504 chars from url ("http://" == 7). */
// If URL does not start with the procotol specification,
// assume http://
// -> tmp[512] -> we can "only" use max 504 chars from url ("http://" == 7).
if ((strncasecmp (url, "http://", 7) != 0) &&
(strncasecmp (url, "https://", 8) != 0) &&
(strncasecmp (url, "exec:", 5) != 0)) {
@ -221,10 +220,10 @@ int UIAddFeed (char * newurl) {
new_ptr = newFeedStruct();
/* getnstr does not return newline... says the docs. */
// getnstr does not return newline... says the docs.
new_ptr->feedurl = malloc (strlen(url)+1);
/* Attach to feed pointer chain. */
// Attach to feed pointer chain.
strncpy (new_ptr->feedurl, url, strlen(url)+1);
new_ptr->next_ptr = first_ptr;
if (first_ptr != NULL)
@ -232,17 +231,17 @@ int UIAddFeed (char * newurl) {
new_ptr->prev_ptr = NULL;
first_ptr = new_ptr;
/* Tag execurl. */
// Tag execurl.
if (strncasecmp (url, "exec:", 5) == 0)
new_ptr->execurl = 1;
if (strncasecmp (url, "smartfeed:", 10) == 0)
new_ptr->smartfeed = 1;
/* Don't need url text anymore. */
// Don't need url text anymore.
free (url);
/* Download new feed and DeXMLize it. */
// Download new feed and DeXMLize it. */
if ((UpdateFeed (new_ptr)) != 0) {
UIStatus (_("The feed could not be parsed. Do you need a filter script for this feed? (y/n)"), 0, 0);
@ -259,23 +258,22 @@ int UIAddFeed (char * newurl) {
}
}
}
return 0;
}
void FeedInfo (struct feed * current_feed) {
int centerx, len;
char *hashme; /* Hashed filename. */
char *hashme; // Hashed filename.
char *file;
char *categories = NULL;
char *url; /* feedurl - authinfo. */
char *url; // feedurl - authinfo.
char *tmp = NULL;
char *tmp2;
struct stat filetest;
url = strdup (current_feed->feedurl);
/* Remove authinfo from URL. */
// Remove authinfo from URL.
tmp = strstr (url, "@");
if (tmp != NULL) {
tmp2 = strstr (url, "://");
@ -305,7 +303,7 @@ void FeedInfo (struct feed * current_feed) {
} else
mvaddstr (9, centerx-(COLS/2-7), _("Not in disk cache."));
/* Print category info */
// Print category info
mvaddstr (10, centerx-(COLS/2-7), _("Categories:"));
if (current_feed->feedcategories == NULL)
mvaddstr (10, centerx-(COLS/2-7)+strlen(_("Categories:"))+1, _("none"));
@ -315,21 +313,21 @@ void FeedInfo (struct feed * current_feed) {
free (categories);
}
/* Tell user if feed uses auth, but don't display the string. */
// Tell user if feed uses auth, but don't display the string.
if (tmp != NULL)
mvaddstr (11, centerx-(COLS/2-7), _("Feed uses authentication."));
else
mvaddstr (11, centerx-(COLS/2-7), _("Feed does not use authentication."));
/* Add a smiley indicator to the http status telling the overall status
so you don't have to know what the HTTP return codes mean.
Yes I think I got the idea from cdparanoia. :) */
// Add a smiley indicator to the http status telling the overall status
// so you don't have to know what the HTTP return codes mean.
// Yes I think I got the idea from cdparanoia. :)
if (current_feed->lasthttpstatus != 0) {
if (current_feed->content_type == NULL) {
len = strlen(_("Last webserver status: %d"));
mvprintw (12, centerx-(COLS/2-7), _("Last webserver status: %d"), current_feed->lasthttpstatus);
} else {
len = strlen(_("Last webserver status: (%s) %d")) + strlen(current_feed->content_type) - 2; /* -2 == %s */
len = strlen(_("Last webserver status: (%s) %d")) + strlen(current_feed->content_type) - 2; // -2 == %s
mvprintw (12, centerx-(COLS/2-7), _("Last webserver status: (%s) %d"),
current_feed->content_type, current_feed->lasthttpstatus);
}
@ -355,7 +353,7 @@ void FeedInfo (struct feed * current_feed) {
}
}
/* Display filter script if any. */
// Display filter script if any.
if (current_feed->perfeedfilter != NULL) {
UISupportDrawBox (5, 13, COLS-6, 14);
attron (WA_REVERSE);
@ -369,7 +367,7 @@ void FeedInfo (struct feed * current_feed) {
free (hashme);
free (url);
/* Wait for the any key. */
// Wait for the any key.
getch();
}
@ -390,7 +388,7 @@ int UIDeleteFeed (char * feedname) {
}
void UIHelpScreen (void) {
int centerx, centery; /* Screen center x/y coordinate. */
int centerx, centery; // Screen center x/y coordinate.
int userinput;
int offset = 18;
int offsetstr = 12;
@ -401,7 +399,7 @@ void UIHelpScreen (void) {
UISupportDrawBox ((COLS/2)-20, (LINES/2)-10, (COLS/2)+24, (LINES/2)+10);
attron (WA_REVERSE);
/* Keys */
// Keys
mvprintw (centery-9, centerx-offset, "%c:", keybindings.addfeed);
mvprintw (centery-8, centerx-offset, "%c:", keybindings.deletefeed);
mvprintw (centery-7, centerx-offset, "%c:", keybindings.changefeedname);
@ -421,7 +419,7 @@ void UIHelpScreen (void) {
mvprintw (centery+7, centerx-offset, "%c:", keybindings.about);
mvprintw (centery+8, centerx-offset, "%c:", 'E');
mvprintw (centery+9, centerx-offset, "%c:", keybindings.quit);
/* Descriptions */
// Descriptions
mvaddstr (centery-9, centerx-offsetstr, _("Add RSS feed..."));
mvaddstr (centery-8, centerx-offsetstr, _("Delete highlighted RSS feed..."));
mvaddstr (centery-7, centerx-offsetstr, _("Rename feed..."));
@ -446,14 +444,13 @@ void UIHelpScreen (void) {
UIStatus (_("Press the any(tm) key to exit help screen."), 0, 0);
userinput = getch();
/* Return input back into input queue so it gets automatically
executed. */
// Return input back into input queue so it gets automatically executed.
if ((userinput != '\n') && (userinput != 'h') && (userinput != 'q'))
ungetch(userinput);
}
void UIDisplayFeedHelp (void) {
int centerx, centery; /* Screen center x/y coordinate. */
int centerx, centery; // Screen center x/y coordinate.
int userinput;
int offset = 18;
int offsetstr = 7;
@ -464,7 +461,7 @@ void UIDisplayFeedHelp (void) {
UISupportDrawBox ((COLS/2)-20, (LINES/2)-6, (COLS/2)+24, (LINES/2)+7);
attron (WA_REVERSE);
/* Keys */
// Keys
mvprintw (centery-5, centerx-offset, _("%c, up:"), keybindings.prev);
mvprintw (centery-4, centerx-offset, _("%c, down:"), keybindings.next);
mvaddstr (centery-3, centerx-offset, _("enter:"));
@ -477,7 +474,7 @@ void UIDisplayFeedHelp (void) {
mvprintw (centery+4, centerx-offset, "%c:", keybindings.feedinfo);
mvaddstr (centery+5, centerx-offset, _("tab:"));
mvprintw (centery+6, centerx-offset, "%c:", keybindings.prevmenu);
/* Descriptions */
// Descriptions
mvprintw (centery-5, centerx-offsetstr, _("Previous item"));
mvprintw (centery-4, centerx-offsetstr, _("Next item"));
mvaddstr (centery-3, centerx-offsetstr, _("View item"));
@ -499,7 +496,7 @@ void UIDisplayFeedHelp (void) {
}
void UIDisplayItemHelp (void) {
int centerx, centery; /* Screen center x/y coordinate. */
int centerx, centery; // Screen center x/y coordinate.
int userinput;
int offset = 16;
int offsetstr = 6;
@ -510,12 +507,12 @@ void UIDisplayItemHelp (void) {
UISupportDrawBox ((COLS/2)-18, (LINES/2)-2, (COLS/2)+18, (LINES/2)+3);
attron (WA_REVERSE);
/* Keys */
// Keys
mvprintw (centery-1, centerx-offset, "%c, <-:", keybindings.prev);
mvprintw (centery, centerx-offset, "%c, ->:", keybindings.next);
mvprintw (centery+1, centerx-offset, "%c:", keybindings.urljump);
mvprintw (centery+2, centerx-offset, _("%c, enter:"), keybindings.prevmenu);
/* Descriptions */
// Descriptions
mvaddstr (centery-1, centerx-offsetstr, _("Previous item"));
mvaddstr (centery, centerx-offsetstr, _("Next item"));
mvaddstr (centery+1, centerx-offsetstr, _("Open link"));
@ -529,7 +526,7 @@ void UIDisplayItemHelp (void) {
}
/* Add/remove categories for given feed. This takes over the main interface while running. */
// Add/remove categories for given feed. This takes over the main interface while running.
void CategorizeFeed (struct feed * current_feed) {
int i, n, nglobal, y;
int uiinput;
@ -538,19 +535,19 @@ void CategorizeFeed (struct feed * current_feed) {
struct feedcategories *category;
struct categories *cur_ptr;
/* Return if we got passed a NULL pointer (no feeds added to main program). */
// Return if we got passed a NULL pointer (no feeds added to main program).
if (current_feed == NULL)
return;
/* Determine number of global categories. */
// Determine number of global categories.
nglobal = 0;
for (cur_ptr = first_category; cur_ptr != NULL; cur_ptr = cur_ptr->next_ptr) {
nglobal++;
}
/* We're taking over the program! */
// We're taking over the program!
while (1) {
/* Determine number of categories for current_feed. */
// Determine number of categories for current_feed.
n = 0;
for (category = current_feed->feedcategories; category != NULL; category = category->next_ptr) {
n++;
@ -563,7 +560,7 @@ void CategorizeFeed (struct feed * current_feed) {
_("Category configuration for %s"), current_feed->title);
/* No category defined yet */
// No category defined yet
if (current_feed->feedcategories == NULL) {
i = 49;
y = 5;
@ -572,7 +569,7 @@ void CategorizeFeed (struct feed * current_feed) {
mvprintw (y+1, (COLS/2)-33, "%c. %s", i, cur_ptr->name);
y++;
i++;
/* Fast forward to 'a' if we hit ASCII 58 ':' */
// Fast forward to 'a' if we hit ASCII 58 ':'
if (i == 58)
i += 39;
}
@ -586,7 +583,7 @@ void CategorizeFeed (struct feed * current_feed) {
mvprintw (y+1, (COLS/2)-33, "%c. %s", i, category->name);
y++;
i++;
/* Fast forward to 'a' if we hit ASCII 58 ':' */
// Fast forward to 'a' if we hit ASCII 58 ':'
if (i == 58)
i += 39;
}
@ -601,7 +598,7 @@ void CategorizeFeed (struct feed * current_feed) {
return;
if (uiinput == 'A') {
if ((n > 0) && (nglobal > 0)) {
/* Clear screen area we want to "draw" to. */
// Clear screen area we want to "draw" to.
UISupportDrawBox ((COLS/2)-37, 5, (COLS/2)+37, 2+3+nglobal+1);
attron (WA_REVERSE);
@ -612,7 +609,7 @@ void CategorizeFeed (struct feed * current_feed) {
mvprintw (y+1, (COLS/2)-33, "%c. %s", i, cur_ptr->name);
y++;
i++;
/* Fast forward to 'a' if we hit ASCII 58 ':' */
// Fast forward to 'a' if we hit ASCII 58 ':'
if (i == 58)
i += 39;
}
@ -624,7 +621,7 @@ void CategorizeFeed (struct feed * current_feed) {
}
if (uiinput == 'A') {
/* Clear screen area we want to "draw" to. */
// Clear screen area we want to "draw" to.
UISupportDrawBox ((COLS/2)-37, 5, (COLS/2)+37, 2+3+nglobal+1);
attron (WA_REVERSE);
@ -640,12 +637,12 @@ void CategorizeFeed (struct feed * current_feed) {
}
free (newcategory);
} else {
/* To add category below. */
// To add category below.
n = 0;
}
}
/* If uiinput is 1-9,a-z
If uiinput < i (ASCII of max selectable element) ignore event. */
// If uiinput is 1-9,a-z
// If uiinput < i (ASCII of max selectable element) ignore event.
if ((((uiinput >= 49) && (uiinput <= 57)) ||
((uiinput >= 97) && (uiinput <= 122))) &&
(uiinput < i)) {
@ -656,43 +653,42 @@ void CategorizeFeed (struct feed * current_feed) {
i = uiinput - 87;
if (n > 0) {
/* Delete category code for n (number of categories defined for current feed) > 0 */
/* Decrease i by one while walking the category linked list.
If we hit 0, break. category->name will now contain the category we want to remove. */
// Delete category code for n (number of categories defined for current feed) > 0
// Decrease i by one while walking the category linked list.
// If we hit 0, break. category->name will now contain the category we want to remove.
for (category = current_feed->feedcategories; category != NULL; category = category->next_ptr) {
if (i == 1)
break;
i--;
}
/* Delete entry from feed categories. */
// Delete entry from feed categories.
FeedCategoryDelete (current_feed, category->name);
} else {
/* If n == 0 add category with number i to feed. */
// If n == 0 add category with number i to feed.
for (cur_ptr = first_category; cur_ptr != NULL; cur_ptr = cur_ptr->next_ptr) {
if (i == 1)
break;
i--;
}
/* Add category to current feed */
// Add category to current feed
FeedCategoryAdd (current_feed, cur_ptr->name);
}
}
}
}
/* Allocates and returns a filter string the user has chosen from the list of
available categories.
If no filter is chosen a NULL pointer is returned. */
// Allocates and returns a filter string the user has chosen from the list of
// available categories.
// If no filter is chosen a NULL pointer is returned.
char * DialogGetCategoryFilter (void) {
int i, nglobal, y;
char *filterstring = NULL;
int uiinput;
struct categories *cur_ptr;
/* Determine number of global categories. */
// Determine number of global categories.
nglobal = 0;
for (cur_ptr = first_category; cur_ptr != NULL; cur_ptr = cur_ptr->next_ptr) {
nglobal++;
@ -709,7 +705,7 @@ char * DialogGetCategoryFilter (void) {
mvprintw (y+1, (COLS/2)-33, "%c. %s", i, cur_ptr->name);
y++;
i++;
/* Fast forward to 'a' if we hit ASCII 58 ':' */
// Fast forward to 'a' if we hit ASCII 58 ':'
if (i == 58)
i += 39;
}
@ -720,8 +716,8 @@ char * DialogGetCategoryFilter (void) {
uiinput = getch();
/* If uiinput is 1-9,a-z
If uiinput < i (ASCII of max selectable element) ignore event. */
// If uiinput is 1-9,a-z
// If uiinput < i (ASCII of max selectable element) ignore event.
if ((((uiinput >= 49) && (uiinput <= 57)) ||
((uiinput >= 97) && (uiinput <= 123))) &&
(uiinput < i)) {
@ -748,7 +744,7 @@ int UIPerFeedFilter (struct feed * current_feed) {
if (current_feed->smartfeed != 0)
return -1;
/* Clear screen area we want to "draw" to. */
// Clear screen area we want to "draw" to.
attron (WA_REVERSE);
UISupportDrawBox (3, 5, COLS-4, 7);
@ -756,13 +752,13 @@ int UIPerFeedFilter (struct feed * current_feed) {
newstring = UIOneLineEntryField (5, 6);
/* If strlen is zero, return 1. */
// If strlen is zero, return 1.
if (strlen(newstring) == 0) {
free (newstring);
return 1;
}
/* If newname contains "|", abort since this is used as a delimiter for the config file. */
// If newname contains "|", abort since this is used as a delimiter for the config file.
if (strstr (newstring, "|") != NULL) {
free (newstring);
return 3;

View File

@ -22,7 +22,7 @@
#include "digcalc.h"
#include <openssl/evp.h>
/* calculate H(A1) as per spec */
// calculate H(A1) as per spec
void DigestCalcHA1 (const char* pszAlg, const char* pszUserName, const char* pszRealm,
const char* pszPassword, const char* pszNonce, const char* pszCNonce,
HASHHEX SessionKey)
@ -54,20 +54,20 @@ void DigestCalcHA1 (const char* pszAlg, const char* pszUserName, const char* psz
sprintf (&SessionKey[2*i], "%02x", md_value[i]);
};
/* calculate request-digest/response-digest as per HTTP Digest spec */
// calculate request-digest/response-digest as per HTTP Digest spec
void DigestCalcResponse(
const HASHHEX HA1, /* H(A1) */
const char* pszNonce, /* nonce from server */
const char* pszNonceCount, /* 8 hex digits */
const char* pszCNonce, /* client nonce */
const char* pszQop, /* qop-value: "", "auth", "auth-int" */
const char* pszMethod, /* method from the request */
const char* pszDigestUri, /* requested URL */
const HASHHEX HEntity, /* H(entity body) if qop="auth-int" */
HASHHEX Response /* request-digest or response-digest */
const HASHHEX HA1, // H(A1)
const char* pszNonce, // nonce from server
const char* pszNonceCount, // 8 hex digits
const char* pszCNonce, // client nonce
const char* pszQop, // qop-value: "", "auth", "auth-int"
const char* pszMethod, // method from the request
const char* pszDigestUri, // requested URL
const HASHHEX HEntity, // H(entity body) if qop="auth-int"
HASHHEX Response // request-digest or response-digest
)
{
/* calculate H(A2) */
// calculate H(A2)
EVP_MD_CTX* mdctx = EVP_MD_CTX_new();
EVP_DigestInit (mdctx, EVP_md5());
EVP_DigestUpdate (mdctx, pszMethod, strlen(pszMethod));
@ -85,7 +85,7 @@ void DigestCalcResponse(
for (unsigned i = 0; i < md_len; ++i)
sprintf (&HA2Hex[2*i], "%02x", md_value[i]);
/* calculate response */
// calculate response
EVP_DigestInit (mdctx, EVP_md5());
EVP_DigestUpdate (mdctx, HA1, HASHHEXLEN);
EVP_DigestUpdate (mdctx, ":", 1);

View File

@ -26,22 +26,22 @@ typedef char HASH[HASHLEN];
#define HASHHEXLEN 32
typedef char HASHHEX[HASHHEXLEN+1];
/* calculate H(A1) as per HTTP Digest spec */
// calculate H(A1) as per HTTP Digest spec
void DigestCalcHA1 (const char* pszAlg, const char* pszUserName, const char* pszRealm,
const char* pszPassword, const char* pszNonce, const char* pszCNonce,
HASHHEX SessionKey);
/* calculate request-digest/response-digest as per HTTP Digest spec */
// calculate request-digest/response-digest as per HTTP Digest spec
void DigestCalcResponse (
const HASHHEX HA1, /* H(A1) */
const char* pszNonce, /* nonce from server */
const char* pszNonceCount, /* 8 hex digits */
const char* pszCNonce, /* client nonce */
const char* pszQop, /* qop-value: "", "auth", "auth-int" */
const char* pszMethod, /* method from the request */
const char* pszDigestUri, /* requested URL */
const HASHHEX HEntity, /* H(entity body) if qop="auth-int" */
HASHHEX Response /* request-digest or response-digest */
const HASHHEX HA1, // H(A1)
const char* pszNonce, // nonce from server
const char* pszNonceCount, // 8 hex digits
const char* pszCNonce, // client nonce
const char* pszQop, // qop-value: "", "auth", "auth-int"
const char* pszMethod, // method from the request
const char* pszDigestUri, // requested URL
const HASHHEX HEntity, // H(entity body) if qop="auth-int"
HASHHEX Response // request-digest or response-digest
);
#endif

View File

@ -33,7 +33,7 @@ int pipe_command_buf(char const *command, char * const argv[],
void const *inbuf, int inbuf_size,
void **outbuf, int *outbuf_size);
/* Load output of local script. Must be valid RSS. */
// Load output of local script. Must be valid RSS.
int FilterExecURL (struct feed * cur_ptr) {
int len = 1;
char *command;
@ -49,7 +49,7 @@ int FilterExecURL (struct feed * cur_ptr) {
snprintf (buf, sizeof(buf), _("Loading \"%s\""), command);
UIStatus (buf, 0, 0);
/* Make room for new stuff. Ah, how I enjoy freeing null pointers! */
// Make room for new stuff. Ah, how I enjoy freeing null pointers!
free (cur_ptr->feed);
cur_ptr->feed = malloc (1);
@ -67,9 +67,9 @@ int FilterExecURL (struct feed * cur_ptr) {
strcat (cur_ptr->feed, buf);
}
/* Set title and link structure to something.
To the feedurl in this case so the program shows something
as placeholder instead of crash. */
// Set title and link structure to something.
// To the feedurl in this case so the program shows something
// as placeholder instead of crash.
if (cur_ptr->title == NULL)
cur_ptr->title = strdup (cur_ptr->feedurl);
if (cur_ptr->link == NULL)
@ -78,16 +78,15 @@ int FilterExecURL (struct feed * cur_ptr) {
pclose (scriptoutput);
free (freeme);
/* Need to set content length so using a filter on an execurl works. */
// Need to set content length so using a filter on an execurl works.
cur_ptr->content_length = strlen(cur_ptr->feed);
return 0;
}
/* Replaces content in cur_ptr->feed with output of script in
* cur_ptr->pipethrough.
* This should probably use pipes, but I couldn't get it to work.
*/
// Replaces content in cur_ptr->feed with output of script in
// cur_ptr->pipethrough.
// This should probably use pipes, but I couldn't get it to work.
int FilterPipe (struct feed * cur_ptr) {
int len = 0;
int retval;
@ -98,16 +97,16 @@ int FilterPipe (struct feed * cur_ptr) {
char tmpfile[] = "/tmp/.snownews.tmp";
FILE *file;
/* Don't call me anymore. */
// Don't call me anymore.
assert(0);
snprintf (command, sizeof(command), "%s < %s", cur_ptr->perfeedfilter, tmpfile);
/* Make sure there is no file with the name we're going to write to. */
// Make sure there is no file with the name we're going to write to.
unlink (tmpfile);
/* Write contents we're going to process to a temp file.
Now use O_EXCL to avoid any tmpfile/symlink attacks. */
// Write contents we're going to process to a temp file.
// Now use O_EXCL to avoid any tmpfile/symlink attacks.
fd = open (tmpfile, O_WRONLY | O_CREAT | O_EXCL, 0600);
if (fd == -1) {
snprintf (tmp, sizeof(tmp), _("Could not write temp file for filter: %s"), strerror(errno));
@ -124,11 +123,11 @@ int FilterPipe (struct feed * cur_ptr) {
cur_ptr->feed = malloc (1);
cur_ptr->feed[0] = '\0';
/* Pipe temp file contents to process and popen it. */
// Pipe temp file contents to process and popen it.
file = popen (command, "r");
while (!feof(file)) {
/* Strange, valgrind blows up if I use the usual fgets() read here. */
// Strange, valgrind blows up if I use the usual fgets() read here.
retval = fread (buf, 1, sizeof(buf), file);
if (retval == 0)
break;
@ -142,7 +141,7 @@ int FilterPipe (struct feed * cur_ptr) {
pclose (file);
/* Clean up. */
// Clean up.
unlink (tmpfile);
return 0;
@ -187,7 +186,7 @@ int FilterPipeNG (struct feed * cur_ptr) {
free (data);
free (command);
free (options); /* options[i] contains only pointers! */
free (options); // options[i] contains only pointers!
return rc;
}
@ -302,4 +301,3 @@ char *pipe_command_string(char const *command, char * const argv[], char const *
return result;
}

File diff suppressed because it is too large Load Diff

View File

@ -167,16 +167,15 @@ void PrintUpdateError (int suppressoutput, struct feed * cur_ptr) {
snprintf(errstr, sizeof(errstr), _("%s: Some error occured for which no specific error message was written."), cur_ptr->title);
break;
}
/* Must be inside if(!suppressoutput) statement! */
// Must be inside if(!suppressoutput) statement!
UIStatus(errstr, 2, 1);
}
printlog(cur_ptr, errstr);
}
/* Update given feed from server.
* Reload XML document and replace in memory cur_ptr->feed with it.
*/
// Update given feed from server.
// Reload XML document and replace in memory cur_ptr->feed with it.
int UpdateFeed (struct feed * cur_ptr) {
char *tmpname;
char *freeme;
@ -184,20 +183,17 @@ int UpdateFeed (struct feed * cur_ptr) {
if (cur_ptr == NULL)
return 1;
/* Smart feeds are generated in the fly. */
// Smart feeds are generated in the fly.
if (cur_ptr->smartfeed == 1)
return 0;
/* If current feed is an exec URL, run that command, otherwise fetch
resource from network. */
// If current feed is an exec URL, run that command, otherwise fetch resource from network.
if (cur_ptr->execurl) {
FilterExecURL (cur_ptr);
} else {
/* Need to work on a copy of ->feedurl, because DownloadFeed()
changes the pointer. */
// Need to work on a copy of ->feedurl, because DownloadFeed() changes the pointer.
tmpname = strdup (cur_ptr->feedurl);
freeme = tmpname; /* Need to make a copy, otherwise we cannot free
all RAM. */
freeme = tmpname; // Need to make a copy, otherwise we cannot free all RAM.
free (cur_ptr->feed);
@ -205,15 +201,15 @@ int UpdateFeed (struct feed * cur_ptr) {
free (freeme);
/* Set title and link structure to something.
* To the feedurl in this case so the program show something
* as placeholder instead of crash. */
// Set title and link structure to something.
// To the feedurl in this case so the program show something
// as placeholder instead of crash.
if (cur_ptr->title == NULL)
cur_ptr->title = strdup (cur_ptr->feedurl);
if (cur_ptr->link == NULL)
cur_ptr->link = strdup (cur_ptr->feedurl);
/* If the download function returns a NULL pointer return from here. */
// If the download function returns a NULL pointer return from here.
if (cur_ptr->feed == NULL) {
if (cur_ptr->problem == 1)
PrintUpdateError (0, cur_ptr);
@ -221,22 +217,22 @@ int UpdateFeed (struct feed * cur_ptr) {
}
}
/* Feed downloaded content through the defined filter. */
// Feed downloaded content through the defined filter.
if (cur_ptr->perfeedfilter != NULL)
FilterPipeNG (cur_ptr);
/* If there is no feed, return. */
// If there is no feed, return.
if (cur_ptr->feed == NULL)
return 1;
if ((DeXML (cur_ptr)) != 0) {
UIStatus (_("Invalid XML! Cannot parse this feed!"), 2, 1);
/* Activate feed problem flag. */
// Activate feed problem flag.
cur_ptr->problem = 1;
return 1;
}
/* We don't need these anymore. Free the raw XML to save some memory. */
// We don't need these anymore. Free the raw XML to save some memory.
free (cur_ptr->feed);
cur_ptr->feed = NULL;
@ -254,17 +250,17 @@ int UpdateAllFeeds (void) {
return 0;
}
/* Load feed from disk. And call UpdateFeed if neccessary. */
// Load feed from disk. And call UpdateFeed if neccessary.
int LoadFeed (struct feed * cur_ptr) {
int len = 0; /* Internal usage for realloc. */
int len = 0; // Internal usage for realloc.
int retval;
char filebuf[4096]; /* File I/O block buffer. */
char filebuf[4096]; // File I/O block buffer.
char file[512];
char *hashme; /* Hashed filename. */
char tmp[1024];
char *hashme; // Hashed filename.
char tmp[1024];
FILE *cache;
/* Smart feeds are generated in the fly. */
// Smart feeds are generated in the fly.
if (cur_ptr->smartfeed == 1)
return 0;
@ -282,9 +278,9 @@ int LoadFeed (struct feed * cur_ptr) {
return 0;
}
/* Read complete cachefile. */
// Read complete cachefile.
while (!feof(cache)) {
/* Use binary read, UTF-8 data! */
// Use binary read, UTF-8 data!
retval = fread (filebuf, 1, sizeof(filebuf), cache);
if (retval == 0)
break;
@ -304,11 +300,11 @@ int LoadFeed (struct feed * cur_ptr) {
fclose (cache);
/* After loading DeXMLize the mess. */
// After loading DeXMLize the mess.
if ((DeXML (cur_ptr)) != 0) {
/* If loading the feed from the disk fails, try downloading from the net. */
// If loading the feed from the disk fails, try downloading from the net.
if ((UpdateFeed (cur_ptr)) != 0) {
/* And if that fails as well, just continue without this feed. */
// And if that fails as well, just continue without this feed.
snprintf (tmp, sizeof(tmp), _("Could not load %s!"), cur_ptr->feedurl);
UIStatus (tmp, 2, 1);
}
@ -322,7 +318,7 @@ int LoadFeed (struct feed * cur_ptr) {
int LoadAllFeeds (int numfeeds) {
float numobjperfeed = 0; /* Number of "progress bar" objects to draw per feed. */
float numobjperfeed = 0; // Number of "progress bar" objects to draw per feed.
int count = 1;
int numobjects = 0;
int oldnumobjects = 0;
@ -336,7 +332,7 @@ int LoadAllFeeds (int numfeeds) {
numobjperfeed = (COLS-titlestrlen-2)/(double) numfeeds;
for (cur_ptr = first_ptr; cur_ptr != NULL; cur_ptr = cur_ptr->next_ptr) {
/* Progress bar */
// Progress bar
numobjects = (count * numobjperfeed) - 2;
if (numobjects < 1)
numobjects = 1;
@ -355,12 +351,11 @@ int LoadAllFeeds (int numfeeds) {
}
/* Write in memory structures to disk cache.
* Usually called before program exit.
*/
// Write in memory structures to disk cache.
// Usually called before program exit.
void WriteCache (void) {
char file[512]; /* File locations. */
char *hashme; /* Cache file name. */
char file[512]; // File locations.
char *hashme; // Cache file name.
char readstatus[2];
char snowdate[32];
char syscall[512];
@ -371,7 +366,7 @@ void WriteCache (void) {
struct stat filetest;
struct feedcategories *category;
char *encoded;
float numobjperfeed = 0; /* Number of "progress bar" objects to draw per feed. */
float numobjperfeed = 0; // Number of "progress bar" objects to draw per feed.
int count = 1;
int numobjects = 0;
int oldnumobjects = 0;
@ -391,7 +386,7 @@ void WriteCache (void) {
snprintf (file, sizeof(file), "%s/.snownews/urls", getenv("HOME"));
/* Make a backup of urls. This approach is really broken! */
// Make a backup of urls. This approach is really broken!
if ((stat (file, &filetest)) != -1) {
if ((filetest.st_mode & S_IFREG) == S_IFREG) {
snprintf (syscall, sizeof(file), "mv -f %s/.snownews/urls %s/.snownews/urls.bak", getenv("HOME"), getenv("HOME"));
@ -405,7 +400,7 @@ void WriteCache (void) {
MainQuit (_("Save settings (urls)"), strerror(errno));
}
/* Unoptimized vs. KISS */
// Unoptimized vs. KISS
for (cur_ptr = first_ptr; cur_ptr != NULL; cur_ptr = cur_ptr->next_ptr)
numfeeds++;
@ -413,7 +408,7 @@ void WriteCache (void) {
numobjperfeed = (COLS-titlestrlen-2)/(double) numfeeds;
for (cur_ptr = first_ptr; cur_ptr != NULL; cur_ptr = cur_ptr->next_ptr) {
/* Progress bar */
// Progress bar
numobjects = (count * numobjperfeed) - 2;
if (numobjects < 1)
numobjects = 1;
@ -434,7 +429,7 @@ void WriteCache (void) {
if (cur_ptr->feedcategories != NULL) {
for (category = cur_ptr->feedcategories; category != NULL; category = category->next_ptr) {
fputs (category->name, configfile);
/* Only add a colon of we run the loop again! */
// Only add a colon of we run the loop again!
if (category->next_ptr != NULL)
fputc (',', configfile);
}
@ -444,15 +439,13 @@ void WriteCache (void) {
if (cur_ptr->perfeedfilter != NULL)
fputs (cur_ptr->perfeedfilter, configfile);
fputc ('\n', configfile); /* Add newline character. */
fputc ('\n', configfile); // Add newline character.
/* Discard smart feeds from cache. */
// Discard smart feeds from cache.
if (cur_ptr->smartfeed)
continue;
/*
* Write cache.
*/
// Write cache.
hashme = Hashify(cur_ptr->feedurl);
snprintf (file, sizeof(file), "%s/.snownews/cache/%s", getenv("HOME"), hashme);
free (hashme);

47
main.c
View File

@ -36,7 +36,7 @@
#include "io-internal.h"
#include "getopt.h"
extern struct feed *first_bak; /* For use with the signal handler. */
extern struct feed *first_bak; // For use with the signal handler.
static int const pid_file_create = 1;
static int const pid_file_delete = 0;
@ -99,15 +99,15 @@ void checkPIDFile (void) {
}
}
/* Deinit ncurses and quit. */
// Deinit ncurses and quit.
void MainQuit (const char * func, const char * error) {
if (error == NULL) {
/* Only save settings if we didn't exit on error. */
// Only save settings if we didn't exit on error.
WriteCache();
}
clear();
refresh();
endwin(); /* Make sure no ncurses function is called after this point! */
endwin(); // Make sure no ncurses function is called after this point!
modifyPIDFile(pid_file_delete);
@ -117,9 +117,9 @@ void MainQuit (const char * func, const char * error) {
if (error == NULL) {
printf (_("Bye.\n\n"));
/* Do this after everything else. If it doesn't work or hang
user can ctrl-c without interfering with the program operation
(like writing caches). */
// Do this after everything else. If it doesn't work or hang
// user can ctrl-c without interfering with the program operation
// (like writing caches).
AutoVersionCheck();
exit(0);
@ -127,29 +127,28 @@ void MainQuit (const char * func, const char * error) {
printf (_("Aborting program execution!\nAn internal error occured. Snownews has quit, no changes has been saved!\n"));
printf (_("This shouldn't happen, please submit a bugreport to kiza@kcore.de, tell me what you where doing and include the output below in your mail.\n"));
printf ("----\n");
/* Please don't localize! I don't want to receive Japanese error messages.
* Thanks. :)
*/
// Please don't localize! I don't want to receive Japanese error messages.
// Thanks. :)
printf ("While executing: %s\n", func);
printf ("Error as reported by the system: %s\n\n", error);
exit(1);
}
}
/* Signal handler function. */
// Signal handler function.
void MainSignalHandler (int sig) {
last_signal = sig;
/* If there is a first_bak!=NULL a filter is set. Reset first_ptr
so the correct list gets written on the disk when exisiting via SIGINT. */
// If there is a first_bak!=NULL a filter is set. Reset first_ptr
// so the correct list gets written on the disk when exisiting via SIGINT.
if (first_bak != NULL)
first_ptr = first_bak;
MainQuit(NULL, NULL);
}
/* Automatic child reaper. */
// Automatic child reaper.
static void sigChildHandler (int sig __attribute__((unused))) {
/* Wait for any child without blocking */
// Wait for any child without blocking
waitpid (-1, NULL, WNOHANG);
}
@ -171,8 +170,8 @@ int main (int argc, char *argv[]) {
struct sigaction act;
#endif
int autoupdate = 0; /* Automatically update feeds on app start... or not if set to 0. */
int numfeeds; /* Number of feeds loaded from Config(). */
int autoupdate = 0; // Automatically update feeds on app start... or not if set to 0.
int numfeeds; // Number of feeds loaded from Config().
int i = 0;
char *arg;
char *foo;
@ -221,20 +220,20 @@ int main (int argc, char *argv[]) {
checkPIDFile();
/* Create PID file. */
// Create PID file.
modifyPIDFile(pid_file_create);
signal (SIGHUP, MainSignalHandler);
signal (SIGINT, MainSignalHandler);
signal (SIGTERM, MainSignalHandler);
/* Un-broken pipify */
// Un-broken pipify
signal (SIGPIPE, SIG_IGN);
signal (SIGCHLD, sigChildHandler);
#ifdef SIGWINCH
/* Set up SIGWINCH handler */
// Set up SIGWINCH handler
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
act.sa_handler = sig_winch;
@ -243,7 +242,7 @@ int main (int argc, char *argv[]) {
InitCurses();
/* Check if configfiles exist and create/read them. */
// Check if configfiles exist and create/read them.
numfeeds = Config();
LoadAllFeeds (numfeeds);
@ -251,13 +250,13 @@ int main (int argc, char *argv[]) {
if (autoupdate)
UpdateAllFeeds();
/* Init the pRNG. See about.c for usages of rand() ;) */
// Init the pRNG. See about.c for usages of rand() ;)
srand(time(0));
/* Give control to main program loop. */
// Give control to main program loop.
UIMainInterface();
/* We really shouldn't be here at all... ah well. */
// We really shouldn't be here at all... ah well.
MainQuit(NULL, NULL);
return 0;
}

View File

@ -30,19 +30,19 @@ char * ConstructBasicAuth (const char * username, const char * password) {
char * authstring;
char * tmpstr;
/* Create base64 authinfo.
// Create base64 authinfo.
RFC 2617. Basic HTTP authentication.
Authorization: Basic username:password[base64 encoded] */
// RFC 2617. Basic HTTP authentication.
// Authorization: Basic username:password[base64 encoded]
/* Construct the cleartext authstring. */
// Construct the cleartext authstring.
len = strlen(username) + 1 + strlen(password) + 1;
authstring = malloc (len);
snprintf (authstring, len, "%s:%s", username, password);
tmpstr = base64encode (authstring, len-1);
/* "Authorization: Basic " + base64str + \r\n\0 */
// "Authorization: Basic " + base64str + \r\n\0
len = 21 + strlen(tmpstr) + 3;
authinfo = malloc (len);
snprintf (authinfo, len, "Authorization: Basic %s\r\n", tmpstr);
@ -61,7 +61,7 @@ char * GetRandomBytes (void) {
devrandom = fopen ("/dev/random", "r");
if (devrandom == NULL) {
/* Use rand() if we don't have access to /dev/random. */
// Use rand() if we don't have access to /dev/random.
for (i = 0; i <= 7; i++) {
raw[i] = 1+(float)rand() / (float)RAND_MAX * 255;
}
@ -78,15 +78,15 @@ char * GetRandomBytes (void) {
}
char * ConstructDigestAuth (char * username, char * password, char * url, char * authdata) {
char * authinfo; /* Authorization header as sent to the server. */
char * authinfo; // Authorization header as sent to the server.
char * token;
int len;
char * realm = NULL; /* Variables for the overcomplicated and annoying HTTP digest algo. */
char * realm = NULL; // Variables for the overcomplicated and annoying HTTP digest algo.
char * qop = NULL;
char * nonce = NULL;
char * opaque = NULL;
char * cnonce;
char szNonceCount[9] = "00000001"; /* Can be always 1 if we never use the same cnonce twice. */
char szNonceCount[9] = "00000001"; // Can be always 1 if we never use the same cnonce twice.
HASHHEX HA1;
HASHHEX HA2 = "";
HASHHEX Response;
@ -125,12 +125,12 @@ char * ConstructDigestAuth (char * username, char * password, char * url, char *
DigestCalcHA1 ("md5", username, realm, password, nonce, cnonce, HA1);
DigestCalcResponse(HA1, nonce, szNonceCount, cnonce, "auth", "GET", url, HA2, Response);
/* Determine length of Authorize header.
*
* Authorization: Digest username="(username)", realm="(realm)",
* nonce="(nonce)", uri="(url)", algorithm=MD5, response="(Response)",
* qop=(auth), nc=(szNonceCount), cnonce="deadbeef"
*/
// Determine length of Authorize header.
//
// Authorization: Digest username="(username)", realm="(realm)",
// nonce="(nonce)", uri="(url)", algorithm=MD5, response="(Response)",
// qop=(auth), nc=(szNonceCount), cnonce="deadbeef"
//
if (opaque == NULL)
len = 32 + strlen(username) + 10 + strlen(realm) + 10 + strlen(nonce) + 8 + strlen(url) + 28 + strlen(Response) + 16 + strlen(szNonceCount) + 10 + strlen(cnonce) + 4 ;
else
@ -156,11 +156,9 @@ char * ConstructDigestAuth (char * username, char * password, char * url, char *
}
/*
Authorization: Digest username="(username)", realm="(realm)",
nonce="(nonce)", uri="(url)", algorithm=MD5, response="(Response)",
qop=(auth), nc=(szNonceCount), cnonce="deadbeef"
*/
// Authorization: Digest username="(username)", realm="(realm)",
// nonce="(nonce)", uri="(url)", algorithm=MD5, response="(Response)",
// qop=(auth), nc=(szNonceCount), cnonce="deadbeef"
int NetSupportAuth (struct feed * cur_ptr, const char * authdata, char * url, const char * netbuf) {
char * header;
char * tmpstr;
@ -169,15 +167,15 @@ int NetSupportAuth (struct feed * cur_ptr, const char * authdata, char * url, co
char * password = NULL;
char * authtype = NULL;
/* Reset cur_ptr->authinfo. */
// Reset cur_ptr->authinfo.
free (cur_ptr->authinfo);
cur_ptr->authinfo = NULL;
/* Catch invalid authdata. */
// Catch invalid authdata.
if (authdata == NULL) {
return 1;
} else if (strchr (authdata, ':') == NULL){
/* No authinfo found in URL. This should not happen. */
// No authinfo found in URL. This should not happen.
return 1;
}
@ -188,16 +186,16 @@ int NetSupportAuth (struct feed * cur_ptr, const char * authdata, char * url, co
username = strdup (freeme);
password = strdup (tmpstr);
/* Free allocated string in tmpstr. */
// Free allocated string in tmpstr.
free (freeme);
/* Extract requested auth type from webserver reply. */
// Extract requested auth type from webserver reply.
header = strdup (netbuf);
freeme = header;
strsep (&header, " ");
authtype = header;
/* Catch invalid server replies. authtype should contain at least _something_. */
// Catch invalid server replies. authtype should contain at least _something_.
if (authtype == NULL) {
free (freeme);
free (username);
@ -206,19 +204,19 @@ int NetSupportAuth (struct feed * cur_ptr, const char * authdata, char * url, co
}
strsep (&header, " ");
/* header now contains:
Basic auth: realm
Digest auth: realm + a lot of other stuff somehow needed by digest auth. */
// header now contains:
// Basic auth: realm
// Digest auth: realm + a lot of other stuff somehow needed by digest auth.
/* Determine auth type the server requests. */
// Determine auth type the server requests.
if (strncasecmp (authtype, "Basic", 5) == 0) {
/* Basic auth. */
// Basic auth.
cur_ptr->authinfo = ConstructBasicAuth (username, password);
} else if (strncasecmp (authtype, "Digest", 6) == 0) {
/* Digest auth. */
// Digest auth.
cur_ptr->authinfo = ConstructDigestAuth (username, password, url, header);
} else {
/* Unkown auth type. */
// Unkown auth type.
free (freeme);
free (username);
free (password);
@ -236,14 +234,13 @@ int NetSupportAuth (struct feed * cur_ptr, const char * authdata, char * url, co
return 0;
}
/* HTTP token may only contain ASCII characters.
*
* Ensure that we don't hit the terminating \0 in a string
* with the for loop.
* The function also ensures that there is no NULL byte in the string.
* If given binary data return at once if we read beyond
* the boundary of sizeof(header).
*/
// HTTP token may only contain ASCII characters.
//
// Ensure that we don't hit the terminating \0 in a string
// with the for loop.
// The function also ensures that there is no NULL byte in the string.
// If given binary data return at once if we read beyond
// the boundary of sizeof(header).
int checkValidHTTPHeader (const unsigned char * header, int size) {
int i, len;
@ -276,4 +273,3 @@ int checkValidHTTPURL (const unsigned char * url) {
return 0;
}

384
netio.c
View File

@ -14,14 +14,14 @@
// You should have received a copy of the GNU General Public License
// along with Snownews. If not, see http://www.gnu.org/licenses/.
/* OS X needs this, otherwise socklen_t is not defined. */
// OS X needs this, otherwise socklen_t is not defined.
#ifdef __APPLE__
# define _BSD_SOCKLEN_T_
#define _BSD_SOCKLEN_T_
#endif
/* BeOS does not define socklen_t. Using uint as suggested by port creator. */
// BeOS does not define socklen_t. Using uint as suggested by port creator.
#ifdef __BEOS__
# define socklen_t unsigned int
#define socklen_t unsigned int
#endif
#include <string.h>
@ -49,29 +49,28 @@
#include "io-internal.h"
#include "zlib_interface.h"
static int const MAX_HTTP_REDIRECTS = 10; /* Maximum number of redirects we will follow. */
static int const NET_TIMEOUT = 20; /* Global network timeout in sec */
static int const MAX_HTTP_REDIRECTS = 10; // Maximum number of redirects we will follow.
static int const NET_TIMEOUT = 20; // Global network timeout in sec
static int const NET_READ = 1;
static int const NET_WRITE = 2;
extern char *proxyname; /* Hostname of proxyserver. */
extern unsigned short proxyport; /* Port on proxyserver to use. */
extern char *proxyname; // Hostname of proxyserver.
extern unsigned short proxyport; // Port on proxyserver to use.
extern char *useragent;
/* Waits NET_TIMEOUT seconds for the socket to return data.
*
* Returns
*
* 0 Socket is ready
* -1 Error occurred (netio_error is set)
*/
// Waits NET_TIMEOUT seconds for the socket to return data.
//
// Returns
//
// 0 Socket is ready
// -1 Error occurred (netio_error is set)
int NetPoll (struct feed * cur_ptr, int * my_socket, int rw) {
fd_set rfdsr;
fd_set rfdsw;
struct timeval tv;
int retval; /* FD_ISSET + assert == Heisenbug? */
int retval; // FD_ISSET + assert == Heisenbug?
/* Set global network timeout */
// Set global network timeout
tv.tv_sec = NET_TIMEOUT;
tv.tv_usec = 0;
@ -81,28 +80,28 @@ int NetPoll (struct feed * cur_ptr, int * my_socket, int rw) {
if (rw == NET_READ) {
FD_SET(*my_socket, &rfdsr);
if (select (*my_socket+1, &rfdsr, NULL, NULL, &tv) == 0) {
/* Timed out */
// Timed out
cur_ptr->netio_error = NET_ERR_TIMEOUT;
return -1;
}
retval = FD_ISSET (*my_socket, &rfdsr);
assert (retval);
if (!retval) {
/* Wtf? */
// Wtf?
cur_ptr->netio_error = NET_ERR_UNKNOWN;
return -1;
}
} else if (rw == NET_WRITE) {
FD_SET(*my_socket, &rfdsw);
if (select (*my_socket+1, NULL, &rfdsw, NULL, &tv) == 0) {
/* Timed out */
// Timed out
cur_ptr->netio_error = NET_ERR_TIMEOUT;
return -1;
}
retval = FD_ISSET (*my_socket, &rfdsw);
assert (retval);
if (!retval) {
/* Wtf? */
// Wtf?
cur_ptr->netio_error = NET_ERR_UNKNOWN;
return -1;
}
@ -115,13 +114,12 @@ int NetPoll (struct feed * cur_ptr, int * my_socket, int rw) {
}
/* Connect network sockets.
*
* Returns
*
* 0 Connected
* -1 Error occured (netio_error is set)
*/
// Connect network sockets.
//
// Returns
//
// 0 Connected
// -1 Error occured (netio_error is set)
int NetConnect (int * my_socket, char * host, struct feed * cur_ptr, int httpproto __attribute__((unused)), int suppressoutput) {
char tmp[512];
struct sockaddr_in address;
@ -144,17 +142,17 @@ int NetConnect (int * my_socket, char * host, struct feed * cur_ptr, int httppro
UIStatus (tmp, 0, 0);
}
/* Create a inet stream TCP socket. */
// Create a inet stream TCP socket.
*my_socket = socket (AF_INET, SOCK_STREAM, 0);
if (*my_socket == -1) {
cur_ptr->netio_error = NET_ERR_SOCK_ERR;
return -1;
}
/* If proxyport is 0 we didn't execute the if http_proxy statement in main
so there is no proxy. On any other value of proxyport do proxyrequests instead. */
// If proxyport is 0 we didn't execute the if http_proxy statement in main
// so there is no proxy. On any other value of proxyport do proxyrequests instead.
if (proxyport == 0) {
/* Lookup remote IP. */
// Lookup remote IP.
remotehost = gethostbyname (realhost);
if (remotehost == NULL) {
close (*my_socket);
@ -163,18 +161,18 @@ int NetConnect (int * my_socket, char * host, struct feed * cur_ptr, int httppro
return -1;
}
/* Set the remote address. */
// Set the remote address.
address.sin_family = AF_INET;
address.sin_port = htons(port);
memcpy (&address.sin_addr.s_addr, remotehost->h_addr_list[0], remotehost->h_length);
/* Connect socket. */
// Connect socket.
cur_ptr->connectresult = connect (*my_socket, (struct sockaddr *) &address, sizeof(address));
/* Check if we're already connected.
BSDs will return 0 on connect even in nonblock if connect was fast enough. */
// Check if we're already connected.
// BSDs will return 0 on connect even in nonblock if connect was fast enough.
if (cur_ptr->connectresult != 0) {
/* If errno is not EINPROGRESS, the connect went wrong. */
// If errno is not EINPROGRESS, the connect went wrong.
if (errno != EINPROGRESS) {
close (*my_socket);
free (realhost);
@ -188,19 +186,19 @@ int NetConnect (int * my_socket, char * host, struct feed * cur_ptr, int httppro
return -1;
}
/* We get errno of connect back via getsockopt SO_ERROR (into connectresult). */
// We get errno of connect back via getsockopt SO_ERROR (into connectresult).
len = sizeof(cur_ptr->connectresult);
getsockopt(*my_socket, SOL_SOCKET, SO_ERROR, &cur_ptr->connectresult, &len);
if (cur_ptr->connectresult != 0) {
close (*my_socket);
free (realhost);
cur_ptr->netio_error = NET_ERR_CONN_FAILED; /* ->strerror(cur_ptr->connectresult) */
cur_ptr->netio_error = NET_ERR_CONN_FAILED; // ->strerror(cur_ptr->connectresult)
return -1;
}
}
} else {
/* Lookup proxyserver IP. */
// Lookup proxyserver IP.
remotehost = gethostbyname (proxyname);
if (remotehost == NULL) {
close (*my_socket);
@ -209,16 +207,16 @@ int NetConnect (int * my_socket, char * host, struct feed * cur_ptr, int httppro
return -1;
}
/* Set the remote address. */
// Set the remote address.
address.sin_family = AF_INET;
address.sin_port = htons(proxyport);
memcpy (&address.sin_addr.s_addr, remotehost->h_addr_list[0], remotehost->h_length);
/* Connect socket. */
// Connect socket.
cur_ptr->connectresult = connect (*my_socket, (struct sockaddr *) &address, sizeof(address));
/* Check if we're already connected.
BSDs will return 0 on connect even in nonblock if connect was fast enough. */
// Check if we're already connected.
// BSDs will return 0 on connect even in nonblock if connect was fast enough.
if (cur_ptr->connectresult != 0) {
if (errno != EINPROGRESS) {
close (*my_socket);
@ -239,7 +237,7 @@ int NetConnect (int * my_socket, char * host, struct feed * cur_ptr, int httppro
if (cur_ptr->connectresult != 0) {
close (*my_socket);
free (realhost);
cur_ptr->netio_error = NET_ERR_CONN_FAILED; /* ->strerror(cur_ptr->connectresult) */
cur_ptr->netio_error = NET_ERR_CONN_FAILED; // ->strerror(cur_ptr->connectresult)
return -1;
}
}
@ -250,45 +248,44 @@ int NetConnect (int * my_socket, char * host, struct feed * cur_ptr, int httppro
}
/*
* Main network function.
* (Now with a useful function description *g*)
*
* This function returns the HTTP request's body (deflating gzip encoded data
* if needed).
* Updates passed feed struct with values gathered from webserver.
* Handles all redirection and HTTP status decoding.
* Returns NULL pointer if no data was received and sets netio_error.
*/
//
// Main network function.
// (Now with a useful function description *g*)
//
// This function returns the HTTP request's body (deflating gzip encoded data
// if needed).
// Updates passed feed struct with values gathered from webserver.
// Handles all redirection and HTTP status decoding.
// Returns NULL pointer if no data was received and sets netio_error.
char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, char * authdata, int httpproto, int suppressoutput) {
char netbuf[4096]; /* Network read buffer. */
char *body; /* XML body. */
char netbuf[4096]; // Network read buffer.
char *body; // XML body.
unsigned int length;
FILE *stream; /* Stream socket. */
FILE *stream; // Stream socket.
#ifdef USE_UNSUPPORTED_AND_BROKEN_CODE
int chunked = 0; /* Content-Encoding: chunked received? */
int chunked = 0; // Content-Encoding: chunked received?
#endif
int redirectcount; /* Number of HTTP redirects followed. */
char httpstatus[4]; /* HTTP status sent by server. */
int redirectcount; // Number of HTTP redirects followed.
char httpstatus[4]; // HTTP status sent by server.
char tmp[256];
char servreply[128]; /* First line of server reply */
char servreply[128]; // First line of server reply
char *tmpstatus;
char *savestart; /* Save start position of pointers. */
char *tmphost; /* Pointers needed to strsep operation. */
char *newhost; /* New hostname if we need to redirect. */
char *newurl; /* New document name ". */
char *savestart; // Save start position of pointers.
char *tmphost; // Pointers needed to strsep operation.
char *newhost; // New hostname if we need to redirect.
char *newurl; // New document name ".
char *newlocation;
char *tmpstring; /* Temp pointers. */
char *tmpstring; // Temp pointers.
char *freeme, *freeme2;
char *redirecttarget;
int retval;
int handled;
int tmphttpstatus;
int inflate = 0; /* Whether feed data needs decompressed with zlib. */
int inflate = 0; // Whether feed data needs decompressed with zlib.
int len;
char * inflatedbody;
int quirksmode = 0; /* IIS operation mode. */
int authfailed = 0; /* Avoid repeating failed auth requests endlessly. */
int quirksmode = 0; // IIS operation mode.
int authfailed = 0; // Avoid repeating failed auth requests endlessly.
int gzipstatus = 0;
@ -303,32 +300,32 @@ char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, c
redirectcount = 0;
/* Goto label to redirect reconnect. */
// Goto label to redirect reconnect.
tryagain:
/* Reconstruct digest authinfo for every request so we don't reuse
the same nonce value for more than one request.
This happens one superflous time on 303 redirects. */
// Reconstruct digest authinfo for every request so we don't reuse
// the same nonce value for more than one request.
// This happens one superflous time on 303 redirects.
if ((cur_ptr->authinfo != NULL) && (cur_ptr->servauth != NULL)) {
if (strstr (cur_ptr->authinfo, " Digest ") != NULL) {
NetSupportAuth(cur_ptr, authdata, url, cur_ptr->servauth);
}
}
/* Open socket. */
// Open socket.
stream = fdopen (*my_socket, "r+");
if (stream == NULL) {
/* This is a serious non-continueable OS error as it will probably not
go away if we retry.
// This is a serious non-continueable OS error as it will probably not
// go away if we retry.
BeOS will stupidly return SUCCESS here making this code silently fail on BeOS. */
// BeOS will stupidly return SUCCESS here making this code silently fail on BeOS.
cur_ptr->netio_error = NET_ERR_SOCK_ERR;
return NULL;
}
/* Again is proxyport == 0, non proxy mode, otherwise make proxy requests. */
// Again is proxyport == 0, non proxy mode, otherwise make proxy requests.
if (proxyport == 0) {
/* Request URL from HTTP server. */
// Request URL from HTTP server.
if (cur_ptr->lastmodified != NULL) {
fprintf(stream,
"GET %s HTTP/1.0\r\nAccept-Encoding: gzip\r\nAccept: application/rdf+xml,application/rss+xml,application/xml,text/xml;q=0.9,*/*;q=0.1\r\nUser-Agent: %s\r\nConnection: close\r\nHost: %s\r\nIf-Modified-Since: %s\r\n%s%s\r\n",
@ -347,9 +344,9 @@ char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, c
(cur_ptr->authinfo ? cur_ptr->authinfo : ""),
(cur_ptr->cookies ? cur_ptr->cookies : ""));
}
fflush(stream); /* We love Solaris, don't we? */
fflush(stream); // We love Solaris, don't we?
} else {
/* Request URL from HTTP server. */
// Request URL from HTTP server.
if (cur_ptr->lastmodified != NULL) {
fprintf(stream,
"GET http://%s%s HTTP/1.0\r\nAccept-Encoding: gzip\r\nAccept: application/rdf+xml,application/rss+xml,application/xml,text/xml;q=0.9,*/*;q=0.1\r\nUser-Agent: %s\r\nConnection: close\r\nHost: %s\r\nIf-Modified-Since: %s\r\n%s%s\r\n",
@ -370,7 +367,7 @@ char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, c
(cur_ptr->authinfo ? cur_ptr->authinfo : ""),
(cur_ptr->cookies ? cur_ptr->cookies : ""));
}
fflush(stream); /* We love Solaris, don't we? */
fflush(stream); // We love Solaris, don't we?
}
if ((NetPoll (cur_ptr, my_socket, NET_READ)) == -1) {
@ -391,16 +388,16 @@ char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, c
tmpstatus = strdup(servreply);
savestart = tmpstatus;
memset (httpstatus, 0, 4); /* Nullify string so valgrind shuts up. */
/* Set pointer to char after first space.
HTTP/1.0 200 OK
^
Copy three bytes into httpstatus. */
memset (httpstatus, 0, 4); // Nullify string so valgrind shuts up.
// Set pointer to char after first space.
// HTTP/1.0 200 OK
// ^
// Copy three bytes into httpstatus.
strsep (&tmpstatus, " ");
if (tmpstatus == NULL) {
cur_ptr->netio_error = NET_ERR_HTTP_PROTO_ERR;
fclose (stream);
free (savestart); /* Probably more leaks when doing auth and abort here. */
free (savestart); // Probably more leaks when doing auth and abort here.
return NULL;
}
strncpy (httpstatus, tmpstatus, 3);
@ -408,8 +405,8 @@ char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, c
cur_ptr->lasthttpstatus = atoi (httpstatus);
/* If the redirectloop was run newhost and newurl were allocated.
We need to free them here. */
// If the redirectloop was run newhost and newurl were allocated.
// We need to free them here.
if ((redirectcount > 0) && (authdata == NULL)) {
free (host);
free (url);
@ -417,30 +414,30 @@ char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, c
tmphttpstatus = cur_ptr->lasthttpstatus;
handled = 1;
/* Check HTTP server response and handle redirects. */
// Check HTTP server response and handle redirects.
do {
switch (tmphttpstatus) {
case 200: /* OK */
/* Received good status from server, clear problem field. */
case 200: // OK
// Received good status from server, clear problem field.
cur_ptr->netio_error = NET_ERR_OK;
cur_ptr->problem = 0;
/* Avoid looping on 20x status codes. */
// Avoid looping on 20x status codes.
handled = 1;
break;
case 300: /* Multiple choice and everything 300 not handled is fatal. */
case 300: // Multiple choice and everything 300 not handled is fatal.
cur_ptr->netio_error = NET_ERR_HTTP_NON_200;
fclose (stream);
return NULL;
case 301:
/* Permanent redirect. Change feed->feedurl to new location.
Done some way down when we have extracted the new url. */
case 302: /* Found */
case 303: /* See Other */
case 307: /* Temp redirect. This is HTTP/1.1 */
// Permanent redirect. Change feed->feedurl to new location.
// Done some way down when we have extracted the new url.
case 302: // Found
case 303: // See Other
case 307: // Temp redirect. This is HTTP/1.1
redirectcount++;
/* Give up if we reach MAX_HTTP_REDIRECTS to avoid loops. */
// Give up if we reach MAX_HTTP_REDIRECTS to avoid loops.
if (redirectcount > MAX_HTTP_REDIRECTS) {
cur_ptr->netio_error = NET_ERR_REDIRECT_COUNT_ERR;
fclose (stream);
@ -449,7 +446,7 @@ char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, c
while (!feof(stream)) {
if ((fgets (netbuf, sizeof(netbuf), stream)) == NULL) {
/* Something bad happened. Server sent stupid stuff. */
// Something bad happened. Server sent stupid stuff.
cur_ptr->netio_error = NET_ERR_HTTP_PROTO_ERR;
fclose (stream);
return NULL;
@ -461,20 +458,20 @@ char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, c
return NULL;
}
/* Split netbuf into hostname and trailing url.
Place hostname in *newhost and tail into *newurl.
Close old connection and reconnect to server.
// Split netbuf into hostname and trailing url.
// Place hostname in *newhost and tail into *newurl.
// Close old connection and reconnect to server.
Do not touch any of the following code! :P */
// Do not touch any of the following code! :P
if (strncasecmp (netbuf, "Location", 8) == 0) {
redirecttarget = strdup (netbuf);
freeme = redirecttarget;
/* Remove trailing \r\n from line. */
// Remove trailing \r\n from line.
redirecttarget[strlen(redirecttarget)-2] = 0;
/* In theory pointer should now be after the space char
after the word "Location:" */
// In theory pointer should now be after the space char
// after the word "Location:"
strsep (&redirecttarget, " ");
if (redirecttarget == NULL) {
@ -485,15 +482,15 @@ char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, c
return NULL;
}
/* Location must start with "http", otherwise switch on quirksmode. */
// Location must start with "http", otherwise switch on quirksmode.
if (strncmp(redirecttarget, "http", 4) != 0)
quirksmode = 1;
/* If the Location header is invalid we need to construct
a correct one here before proceeding with the program.
This makes headers like
"Location: fuck-the-protocol.rdf" work.
In violalation of RFC1945, RFC2616. */
// If the Location header is invalid we need to construct
// a correct one here before proceeding with the program.
// This makes headers like
// "Location: protocol.rdf" work.
// In violalation of RFC1945, RFC2616.
if (quirksmode) {
len = 7 + strlen(host) + strlen(redirecttarget) + 3;
newlocation = malloc(len);
@ -506,12 +503,12 @@ char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, c
} else
newlocation = strdup (redirecttarget);
/* This also frees redirecttarget. */
// This also frees redirecttarget.
free (freeme);
/* Change cur_ptr->feedurl on 301. */
// Change cur_ptr->feedurl on 301.
if (cur_ptr->lasthttpstatus == 301) {
/* Check for valid redirection URL */
// Check for valid redirection URL
if (checkValidHTTPURL((unsigned char *)newlocation) != 0) {
cur_ptr->problem = 1;
cur_ptr->netio_error = NET_ERR_REDIRECT_ERR;
@ -526,7 +523,7 @@ char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, c
if (authdata == NULL)
cur_ptr->feedurl = strdup (newlocation);
else {
/* Include authdata in newly constructed URL. */
// Include authdata in newly constructed URL.
len = strlen(authdata) + strlen(newlocation) + 2;
cur_ptr->feedurl = malloc (len);
newurl = strdup(newlocation);
@ -542,15 +539,15 @@ char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, c
strsep (&newlocation, "/");
strsep (&newlocation, "/");
tmphost = newlocation;
/* The following line \0-terminates tmphost in overwriting the first
/ after the hostname. */
// The following line \0-terminates tmphost in overwriting the first
// / after the hostname.
strsep (&newlocation, "/");
/* newlocation must now be the absolute path on newhost.
If not we've been redirected to somewhere totally stupid
(oh yeah, no offsite linking, go to our fucking front page).
Say goodbye to the webserver in this case. In fact, we don't
even say goodbye, but just drop the connection. */
// newlocation must now be the absolute path on newhost.
// If not we've been redirected to somewhere unexpected
// (oh yeah, no offsite linking, go to our front page).
// Say goodbye to the webserver in this case. In fact, we don't
// even say goodbye, but just drop the connection.
if (newlocation == NULL) {
cur_ptr->netio_error = NET_ERR_REDIRECT_ERR;
fclose (stream);
@ -564,10 +561,10 @@ char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, c
free (freeme);
/* Close connection. */
// Close connection.
fclose (stream);
/* Reconnect to server. */
// Reconnect to server.
if ((NetConnect (my_socket, newhost, cur_ptr, httpproto, suppressoutput)) != 0) {
return NULL;
}
@ -580,30 +577,30 @@ char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, c
}
break;
case 304:
/* Not modified received. We can close stream and return from here.
Not very friendly though. :) */
// Not modified received. We can close stream and return from here.
// Not very friendly though. :)
fclose (stream);
/* Received good status from server, clear problem field. */
// Received good status from server, clear problem field.
cur_ptr->netio_error = NET_ERR_OK;
cur_ptr->problem = 0;
/* This should be freed everywhere where we return
and current feed uses auth. */
// This should be freed everywhere where we return
// and current feed uses auth.
if ((redirectcount > 0) && (authdata != NULL)) {
free (host);
free (url);
}
return NULL;
case 401:
/* Authorization.
Parse rest of header and rerequest URL from server using auth mechanism
requested in WWW-Authenticate header field. (Basic or Digest) */
// Authorization.
// Parse rest of header and rerequest URL from server using auth mechanism
// requested in WWW-Authenticate header field. (Basic or Digest)
break;
case 404:
cur_ptr->netio_error = NET_ERR_HTTP_404;
fclose (stream);
return NULL;
case 410: /* The feed is gone. Politely remind the user to unsubscribe. */
case 410: // The feed is gone. Politely remind the user to unsubscribe.
cur_ptr->netio_error = NET_ERR_HTTP_410;
fclose (stream);
return NULL;
@ -612,13 +609,13 @@ char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, c
fclose (stream);
return NULL;
default:
/* unknown error codes have to be treated like the base class */
// unknown error codes have to be treated like the base class
if (handled) {
/* first pass, modify error code to base class */
// first pass, modify error code to base class
handled = 0;
tmphttpstatus -= tmphttpstatus % 100;
} else {
/* second pass, give up on unknown error base class */
// second pass, give up on unknown error base class
cur_ptr->netio_error = NET_ERR_HTTP_NON_200;
printlog (cur_ptr, servreply);
fclose (stream);
@ -627,7 +624,7 @@ char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, c
}
} while(!handled);
/* Read rest of HTTP header and parse what we need. */
// Read rest of HTTP header and parse what we need.
while (!feof(stream)) {
if ((NetPoll (cur_ptr, my_socket, NET_READ)) == -1) {
fclose (stream);
@ -644,11 +641,11 @@ char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, c
}
if (strncasecmp (netbuf, "Transfer-Encoding", 17) == 0) {
/* Chunked transfer encoding. HTTP/1.1 extension.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1 */
/* This is not supported, because the contributed dechunk function
does not work with binary data and fails valgrind tests.
Disabled as of 1.5.7. */
// Chunked transfer encoding. HTTP/1.1 extension.
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1
// This is not supported, because the contributed dechunk function
// does not work with binary data and fails valgrind tests.
// Disabled as of 1.5.7.
#ifdef USE_UNSUPPORTED_AND_BROKEN_CODE
#warning ===The function decodedechunked() is not safe for binary data. Since you specifically requested it to be compiled in you probably know better what you are doing than me. Do not report bugs for this code.===
if (strstr (netbuf, "chunked") != NULL)
@ -660,7 +657,7 @@ char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, c
return NULL;
#endif
}
/* Get last modified date. This is only relevant on HTTP 200. */
// Get last modified date. This is only relevant on HTTP 200.
if ((strncasecmp (netbuf, "Last-Modified", 13) == 0) &&
(cur_ptr->lasthttpstatus == 200)) {
tmpstring = strdup(netbuf);
@ -702,19 +699,19 @@ char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, c
free(freeme);
}
}
/* HTTP authentication
*
* RFC 2617 */
// HTTP authentication
//
// RFC 2617
if ((strncasecmp (netbuf, "WWW-Authenticate", 16) == 0) &&
(cur_ptr->lasthttpstatus == 401)) {
if (authfailed) {
/* Don't repeat authrequest if it already failed before! */
// Don't repeat authrequest if it already failed before!
cur_ptr->netio_error = NET_ERR_AUTH_FAILED;
fclose (stream);
return NULL;
}
/* Remove trailing \r\n from line. */
// Remove trailing \r\n from line.
if (netbuf[strlen(netbuf)-1] == '\n')
netbuf[strlen(netbuf)-1] = '\0';
if (netbuf[strlen(netbuf)-1] == '\r')
@ -722,13 +719,13 @@ char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, c
authfailed++;
/* Make a copy of the WWW-Authenticate header. We use it to
reconstruct a new auth reply on every loop. */
// Make a copy of the WWW-Authenticate header. We use it to
// reconstruct a new auth reply on every loop.
free (cur_ptr->servauth);
cur_ptr->servauth = strdup (netbuf);
/* Load authinfo into cur_ptr->authinfo. */
// Load authinfo into cur_ptr->authinfo.
retval = NetSupportAuth(cur_ptr, authdata, url, netbuf);
switch (retval) {
@ -750,57 +747,54 @@ char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, c
default:
break;
}
/* Close current connection and reconnect to server. */
// Close current connection and reconnect to server.
fclose (stream);
if ((NetConnect (my_socket, host, cur_ptr, httpproto, suppressoutput)) != 0) {
return NULL;
}
/* Now that we have an authinfo, repeat the current request. */
// Now that we have an authinfo, repeat the current request.
goto tryagain;
}
/* This seems to be optional and probably not worth the effort since we
don't issue a lot of consecutive requests. */
/*if ((strncasecmp (netbuf, "Authentication-Info", 19) == 0) ||
(cur_ptr->lasthttpstatus == 200)) {
// This seems to be optional and probably not worth the effort since we
// don't issue a lot of consecutive requests.
//if ((strncasecmp (netbuf, "Authentication-Info", 19) == 0) || (cur_ptr->lasthttpstatus == 200)) {}
}*/
/* HTTP RFC 2616, Section 19.3 Tolerant Applications.
Accept CRLF and LF line ends in the header field. */
// HTTP RFC 2616, Section 19.3 Tolerant Applications.
// Accept CRLF and LF line ends in the header field.
if ((strcmp(netbuf, "\r\n") == 0) || (strcmp(netbuf, "\n") == 0))
break;
}
/* If the redirectloop was run newhost and newurl were allocated.
We need to free them here.
But _after_ the authentication code since it needs these values! */
// If the redirectloop was run newhost and newurl were allocated.
// We need to free them here.
// But _after_ the authentication code since it needs these values!
if ((redirectcount > 0) && (authdata != NULL)) {
free (host);
free (url);
}
/**********************
* End of HTTP header *
**********************/
//---------------------
// End of HTTP header
//---------------------
/* Init pointer so strncat works.
Workaround class hack. */
// Init pointer so strncat works.
// Workaround class hack.
body = malloc(1);
body[0] = '\0';
length = 0;
/* Read stream until EOF and return it to parent. */
// Read stream until EOF and return it to parent.
while (!feof(stream)) {
if ((NetPoll (cur_ptr, my_socket, NET_READ)) == -1) {
fclose (stream);
return NULL;
}
/* Since we handle binary data if we read compressed input we
need to use fread instead of fgets after reading the header. */
// Since we handle binary data if we read compressed input we
// need to use fread instead of fgets after reading the header.
retval = fread (netbuf, 1, sizeof(netbuf), stream);
if (retval == 0)
break;
@ -815,7 +809,7 @@ char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, c
cur_ptr->content_length = length;
/* Close connection. */
// Close connection.
fclose (stream);
#ifdef USE_UNSUPPORTED_AND_BROKEN_CODE
@ -828,9 +822,9 @@ char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, c
}
#endif
/* If inflate==1 we need to decompress the content.. */
// If inflate==1 we need to decompress the content..
if (inflate == 1) {
/* gzipinflate */
// gzipinflate
gzipstatus = jg_gzip_uncompress (body, length, (void **)&inflatedbody, &cur_ptr->content_length);
if (gzipstatus != 0) {
char errstr[255];
@ -841,7 +835,7 @@ char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, c
return NULL;
}
/* Copy uncompressed data back to body. */
// Copy uncompressed data back to body.
free (body);
body = inflatedbody;
}
@ -849,26 +843,26 @@ char * NetIO (int * my_socket, char * host, char * url, struct feed * cur_ptr, c
return body;
}
/* Returns allocated string with body of webserver reply.
Various status info put into struct feed * cur_ptr.
Set suppressoutput=1 to disable ncurses calls. */
// Returns allocated string with body of webserver reply.
// Various status info put into struct feed * cur_ptr.
// Set suppressoutput=1 to disable ncurses calls.
char * DownloadFeed (char * url, struct feed * cur_ptr, int suppressoutput) {
int my_socket = 0;
int url_fixup = 0;
char *host; /* Needs to freed. */
char *host; // Needs to freed.
char *tmphost;
char *freeme;
char *returndata;
char *authdata = NULL;
char *tmpstr;
int httpproto = 0; /* 0: http; 1: https */
int httpproto = 0; // 0: http; 1: https
if (checkValidHTTPURL((unsigned char *)url) != 0) {
cur_ptr->problem = 1;
cur_ptr->netio_error = NET_ERR_HTTP_PROTO_ERR;
return NULL;
}
/* strstr will match _any_ substring. Not good, use strncasecmp with length 5! */
// strstr will match _any_ substring. Not good, use strncasecmp with length 5!
if (strncasecmp (url, "https", 5) == 0)
httpproto = 1;
else
@ -879,12 +873,12 @@ char * DownloadFeed (char * url, struct feed * cur_ptr, int suppressoutput) {
tmphost = url;
strsep (&url, "/");
if (url == NULL) {
/* Assume "/" is input is exhausted. */
// Assume "/" is input is exhausted.
url = strdup("/");
url_fixup = 1;
}
/* If tmphost contains an '@', extract username and pwd. */
// If tmphost contains an '@', extract username and pwd.
if (strchr (tmphost, '@') != NULL) {
tmpstr = tmphost;
strsep (&tmphost, "@");
@ -893,10 +887,10 @@ char * DownloadFeed (char * url, struct feed * cur_ptr, int suppressoutput) {
host = strdup (tmphost);
/* netio() might change pointer of host to something else if redirect
loop is executed. Make a copy so we can correctly free everything. */
// netio() might change pointer of host to something else if redirect
// loop is executed. Make a copy so we can correctly free everything.
freeme = host;
/* Only run if url was != NULL above. */
// Only run if url was != NULL above.
if (!url_fixup) {
url--;
url[0] = '/';
@ -918,8 +912,8 @@ char * DownloadFeed (char * url, struct feed * cur_ptr, int suppressoutput) {
cur_ptr->problem = 1;
}
/* url will be freed in the calling function. */
free (freeme); /* This is *host. */
// url will be freed in the calling function.
free (freeme); // This is *host.
free (authdata);
if (url_fixup)
free(url);

View File

@ -23,16 +23,16 @@ char * DownloadFeed (char * url, struct feed * cur_ptr, int suppressoutput);
typedef enum {
NET_ERR_OK,
/* Init errors */
// Init errors
NET_ERR_URL_INVALID,
/* Connect errors */
// Connect errors
NET_ERR_SOCK_ERR,
NET_ERR_HOST_NOT_FOUND,
NET_ERR_CONN_REFUSED,
NET_ERR_CONN_FAILED,
NET_ERR_TIMEOUT,
NET_ERR_UNKNOWN,
/* Transfer errors */
// Transfer errors
NET_ERR_REDIRECT_COUNT_ERR,
NET_ERR_REDIRECT_ERR,
NET_ERR_HTTP_410,

View File

@ -22,20 +22,19 @@
#include "main.h"
/******************************************************************************
* This is a replacement for strsep which is not portable (missing on Solaris).
*
* http://www.winehq.com/hypermail/wine-patches/2001/11/0024.html
*
* The following function was written by François Gouget.
*/
//-----------------------------------------------------------------------------
// This is a replacement for strsep which is not portable (missing on Solaris).
//
// http://www.winehq.com/hypermail/wine-patches/2001/11/0024.html
//
// The following function was written by Francois Gouget.
#ifdef SUN
char* strsep (char** str, const char* delims)
{
char* token;
if (*str==NULL) {
/* No more tokens */
// No more tokens
return NULL;
}
@ -48,12 +47,12 @@ char* strsep (char** str, const char* delims)
}
(*str)++;
}
/* There is no other token */
// There is no other token
*str=NULL;
return token;
}
/* timegm() is not available on Solaris */
// timegm() is not available on Solaris
time_t timegm(struct tm *t)
{
time_t tl, tb;
@ -65,7 +64,7 @@ time_t timegm(struct tm *t)
t->tm_hour--;
tl = mktime (t);
if (tl == -1)
return -1; /* can't deal with output from strptime */
return -1; // can't deal with output from strptime
tl += 3600;
}
tg = gmtime (&tl);
@ -76,14 +75,14 @@ time_t timegm(struct tm *t)
tg->tm_hour--;
tb = mktime (tg);
if (tb == -1)
return -1; /* can't deal with output from gmtime */
return -1; // can't deal with output from gmtime
tb += 3600;
}
return (tl - (tb - tl));
}
#endif
/* strcasestr stolen from: http://www.unixpapa.com/incnote/string.html */
// strcasestr stolen from: http://www.unixpapa.com/incnote/string.html
const char* s_strcasestr (const char* a, const char* b) {
const size_t lena = strlen(a), lenb = strlen(b);
char f[3];
@ -95,7 +94,7 @@ const char* s_strcasestr (const char* a, const char* b) {
}
/* Private malloc wrapper. Aborts program execution if malloc fails. */
// Private malloc wrapper. Aborts program execution if malloc fails.
void* s_malloc (size_t size) {
void* newmem = malloc (size);
if (!newmem)

184
setup.c
View File

@ -39,13 +39,13 @@ struct entity *first_entity = NULL;
struct keybindings keybindings;
struct color color;
char *browser; /* Browser command. lynx is standard. */
char *proxyname; /* Hostname of proxyserver. */
char *useragent; /* Snownews User-Agent string. */
unsigned short proxyport = 0; /* Port on proxyserver to use. */
int use_colors = 1; /* Default to enabled. */
char *browser; // Browser command. lynx is standard.
char *proxyname; // Hostname of proxyserver.
char *useragent; // Snownews User-Agent string.
unsigned short proxyport = 0; // Port on proxyserver to use.
int use_colors = 1; // Default to enabled.
/* Load browser command from ~./snownews/browser. */
// Load browser command from ~./snownews/browser.
void SetupBrowser (const char * file) {
char filebuf[256];
FILE *configfile;
@ -55,32 +55,32 @@ void SetupBrowser (const char * file) {
UIStatus (_("Creating new config \"browser\"..."), 0, 0);
configfile = fopen (file, "w+");
if (configfile == NULL)
MainQuit (_("Create initial configfile \"config\""), strerror(errno)); /* Still didn't work? */
MainQuit (_("Create initial configfile \"config\""), strerror(errno)); // Still didn't work?
browser = strdup("lynx %s");
fputs (browser, configfile);
fclose (configfile);
} else {
/* Careful not to overflow char browser! */
// Careful not to overflow char browser!
fgets (filebuf, sizeof(filebuf), configfile);
browser = strdup(filebuf);
fclose (configfile);
/* Die newline, die! */
// Die newline, die!
if (browser[strlen(browser)-1] == '\n')
browser[strlen(browser)-1] = '\0';
}
}
/* Parse http_proxy environment variable and define proxyname and proxyport. */
// Parse http_proxy environment variable and define proxyname and proxyport.
void SetupProxy (void) {
char *freeme;
char *proxystring;
char *tmp;
/* Check for proxy environment variable. */
// Check for proxy environment variable.
if (getenv("http_proxy") != NULL) {
/* The pointer returned by getenv must not be altered.
What about mentioning this in the manpage of getenv? */
// The pointer returned by getenv must not be altered.
// What about mentioning this in the manpage of getenv?
proxystring = strdup(getenv("http_proxy"));
freeme = proxystring;
strsep (&proxystring, "/");
@ -108,8 +108,8 @@ void SetupProxy (void) {
}
/* Construct the user agent string that snownews sends to the webserver.
This includes Snownews/VERSION, OS name and language setting. */
// Construct the user agent string that snownews sends to the webserver.
// This includes Snownews/VERSION, OS name and language setting.
void SetupUserAgent (void) {
char *lang;
char url[] = "http://snownews.kcore.de/";
@ -117,32 +117,32 @@ void SetupUserAgent (void) {
urllen = strlen(url);
/* Constuct the User-Agent string of snownews. This is done here in program init,
because we need to do it exactly once and it will never change while the program
is running. */
// Constuct the User-Agent string of snownews. This is done here in program init,
// because we need to do it exactly once and it will never change while the program
// is running.
if (getenv("LANG") != NULL) {
lang = getenv("LANG");
/* Snonews/VERSION (Linux; de_DE; (http://kiza.kcore.de/software/snownews/) */
// Snonews/VERSION (Linux; de_DE; (http://kiza.kcore.de/software/snownews/)
ualen = strlen("Snownews/") + strlen(VERSION) + 2 + strlen(lang) + 2 + strlen(OS)+2 + urllen + 2;
useragent = malloc(ualen);
snprintf (useragent, ualen, "Snownews/%s (%s; %s; %s)", VERSION, OS, lang, url);
} else {
/* "Snownews/" + VERSION + "(http://kiza.kcore.de/software/snownews/)" */
// "Snownews/" + VERSION + "(http://kiza.kcore.de/software/snownews/)"
ualen = strlen("Snownews/") + strlen(VERSION) + 2 + strlen(OS) + 2 + urllen + 2;
useragent = malloc(ualen);
snprintf (useragent, ualen, "Snownews/%s (%s; %s)", VERSION, OS, url);
}
}
/* Define global keybindings and load user customized bindings. */
// Define global keybindings and load user customized bindings.
void SetupKeybindings (const char * file) {
char filebuf[128];
char *freeme, *tmpbuf;
FILE *configfile;
/* Define default values for keybindings. If some are defined differently
in the keybindings file they will be overwritten. If some are missing or broken/wrong
these are sane defaults. */
// Define default values for keybindings. If some are defined differently
// in the keybindings file they will be overwritten. If some are missing or broken/wrong
// these are sane defaults.
keybindings.next = 'n';
keybindings.prev = 'p';
keybindings.prevmenu = 'q';
@ -182,17 +182,17 @@ void SetupKeybindings (const char * file) {
configfile = fopen (file, "r");
if (configfile != NULL) {
/* Read keybindings and populate keybindings struct. */
// Read keybindings and populate keybindings struct.
while (!feof(configfile)) {
if ((fgets (filebuf, sizeof(filebuf), configfile)) == NULL)
break;
if (strstr(filebuf, "#") != NULL)
continue;
tmpbuf = strdup(filebuf); /* strsep only works on *ptr */
freeme = tmpbuf; /* Save start pos. This is also the string we need to compare. strsep will \0 the delimiter. */
tmpbuf = strdup(filebuf); // strsep only works on *ptr
freeme = tmpbuf; // Save start pos. This is also the string we need to compare. strsep will \0 the delimiter.
strsep (&tmpbuf, ":");
/* Munch trailing newline and avoid \n being bound to a function if no key is defined. */
// Munch trailing newline and avoid \n being bound to a function if no key is defined.
if (tmpbuf != NULL)
tmpbuf[strlen(tmpbuf)-1] = 0;
@ -270,8 +270,8 @@ void SetupKeybindings (const char * file) {
free (freeme);
}
/* Override old default settings and make sure there is no clash. */
/* Default browser is now B; b moved to page up. */
// Override old default settings and make sure there is no clash.
// Default browser is now B; b moved to page up.
if (keybindings.dfltbrowser == 'b') {
keybindings.dfltbrowser = 'B';
}
@ -321,7 +321,7 @@ void SetupKeybindings (const char * file) {
fclose (configfile);
}
/* Set up colors and load user customized colors. */
// Set up colors and load user customized colors.
void SetupColors (const char * file) {
char filebuf[128];
char *freeme, *tmpbuf;
@ -336,18 +336,18 @@ void SetupColors (const char * file) {
configfile = fopen (file, "r");
/* If there is a config file, read it. */
// If there is a config file, read it.
if (configfile != NULL) {
while (!feof(configfile)) {
if ((fgets (filebuf, sizeof(filebuf), configfile)) == NULL)
break;
if (strstr(filebuf, "#") != NULL)
continue;
tmpbuf = strdup(filebuf); /* strsep only works on *ptr */
freeme = tmpbuf; /* Save start pos. This is also the string we need to compare. strsep will \0 the delimiter. */
tmpbuf = strdup(filebuf); // strsep only works on *ptr
freeme = tmpbuf; // Save start pos. This is also the string we need to compare. strsep will \0 the delimiter.
strsep (&tmpbuf, ":");
/* Munch trailing newline. */
// Munch trailing newline.
if (tmpbuf != NULL)
tmpbuf[strlen(tmpbuf)-1] = 0;
@ -380,8 +380,8 @@ void SetupColors (const char * file) {
fclose (configfile);
}
/* Write the file. This will write all setting with their
values read before and new ones with the defaults. */
// Write the file. This will write all setting with their
// values read before and new ones with the defaults.
configfile = fopen (file, "w+");
fputs ("# Snownews color definitons\n", configfile);
fputs ("# black:0\n", configfile);
@ -409,37 +409,37 @@ void SetupColors (const char * file) {
if (use_colors) {
start_color();
/* The following call will automagically implement -1 as the terminal's
default color for fg/bg in init_pair. */
// The following call will automagically implement -1 as the terminal's
// default color for fg/bg in init_pair.
use_default_colors();
/* Internally used color pairs.
Use with WA_BOLD to get bright color (orange->yellow, gray->white, etc). */
init_pair (10, 1, -1); /* red */
init_pair (11, 2, -1); /* green */
init_pair (12, 3, -1); /* orange */
init_pair (13, 4, -1); /* blue */
init_pair (14, 5, -1); /* magenta */
init_pair (15, 6, -1); /* cyan */
init_pair (16, 7, -1); /* gray */
// Internally used color pairs.
// Use with WA_BOLD to get bright color (orange->yellow, gray->white, etc).
init_pair (10, 1, -1); // red
init_pair (11, 2, -1); // green
init_pair (12, 3, -1); // orange
init_pair (13, 4, -1); // blue
init_pair (14, 5, -1); // magenta
init_pair (15, 6, -1); // cyan
init_pair (16, 7, -1); // gray
/* Default terminal color color pair */
// Default terminal color color pair
init_pair (63, -1, -1);
/* Initialize all color pairs we're gonna use. */
/* New item. */
// Initialize all color pairs we're gonna use.
// New item.
if (color.newitemsbold == 1)
init_pair (2, color.newitems-8, -1);
else
init_pair (2, color.newitems, -1);
/* Goto url line */
// Goto url line
if (color.urljumpbold == 1)
init_pair (3, color.urljump-8, -1);
else
init_pair (3, color.urljump, -1);
/* Feed title header */
// Feed title header
if (color.feedtitlebold == 1)
init_pair (4, color.feedtitle-8, -1);
else
@ -449,7 +449,7 @@ void SetupColors (const char * file) {
}
/* Load user customized entity conversion table. */
// Load user customized entity conversion table.
void SetupEntities (const char * file) {
char filebuf[128];
char *freeme, *tmpbuf, *tmppos;
@ -469,9 +469,10 @@ void SetupEntities (const char * file) {
fputs ("# \n", configfile);
fputs ("# XML defined entities are converted by default. These are:\n# &amp;, &lt;, &gt;, &apos;, &quot;\n", configfile);
fputs ("# \n", configfile);
fputs ("&auml;ä\n&ouml;ö\n&uuml;ü\n", configfile);
fputs ("&Auml;Ä\n&Ouml;Ö\n&Uuml;Ü\n", configfile);
fputs ("&szlig;ß\n&nbsp; \n&mdash;--\n&hellip;...\n&#8220;\"\n&#8221;\"\n", configfile);
fprintf (configfile, "&auml;%c\n&ouml;%c\n&uuml;%c\n", 0xe4, 0xf6, 0xfc); // umlauted a,o,u
fprintf (configfile, "&Auml;%c\n&Ouml;%c\n&Uuml;%c\n", 0xc4, 0xd6, 0xdc); // umlauted A,O,U
fprintf (configfile, "&szlig;%c\n", 0xdf); // german b
fputs ("&nbsp; \n&mdash;--\n&hellip;...\n&#8220;\"\n&#8221;\"\n", configfile);
fputs ("&raquo;\"\n&laquo;\"\n", configfile);
fclose (configfile);
@ -482,22 +483,22 @@ void SetupEntities (const char * file) {
if ((fgets (filebuf, sizeof(filebuf), configfile)) == NULL)
break;
/* Discard comment lines. */
// Discard comment lines.
if (filebuf[0] == '#')
continue;
/* Entities must start with '&', otherwise discard. */
// Entities must start with '&', otherwise discard.
if (filebuf[0] == '&') {
entity = malloc (sizeof (struct entity));
tmpbuf = strdup (filebuf);
freeme = tmpbuf;
/* Munch trailing newline. */
// Munch trailing newline.
if (tmpbuf[strlen(tmpbuf)-1] == '\n')
tmpbuf[strlen(tmpbuf)-1] = '\0';
/* Delete starting '&' and set pointer to beginning of entity. */
// Delete starting '&' and set pointer to beginning of entity.
tmpbuf[0] = '\0';
tmpbuf++;
tmppos = tmpbuf;
@ -511,7 +512,7 @@ void SetupEntities (const char * file) {
free (freeme);
/* Add entity to linked list structure. */
// Add entity to linked list structure.
if (first_entity == NULL)
first_entity = entity;
else {
@ -524,38 +525,37 @@ void SetupEntities (const char * file) {
}
}
/* Create snownews' config directories if they do not exist yet,
load global configuration settings and caches.
Returns number of feeds successfully loaded. */
// Create snownews' config directories if they do not exist yet,
// load global configuration settings and caches.
//
// Returns number of feeds successfully loaded.
//
int Config (void) {
char file[512]; /* File locations. */
char file[512]; // File locations.
char filebuf[2048];
char *freeme, *tmpbuf, *tmppos, *tmpstr;
char *categories = NULL; /* Holds comma seperated category string. */
char *categories = NULL; // Holds comma seperated category string.
FILE *configfile;
FILE *errorlog;
struct feed *new_ptr;
struct stat dirtest;
int numfeeds = 0; /* Number of feeds we have. */
int numfeeds = 0; // Number of feeds we have.
SetupProxy();
SetupUserAgent();
/* Set umask to 077 for all created files. */
// Set umask to 077 for all created files.
umask(63);
/*
* Setup config directories.
*/
// Setup config directories.
snprintf (file, sizeof(file), "%s/.snownews", getenv("HOME"));
if ((stat (file, &dirtest)) == -1 ) {
/* Create directory. */
// Create directory.
if (mkdir (file, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0)
MainQuit ("Creating config directory ~/.snownews/", strerror(errno));
} else {
/* Something with the name .snownews exists, let's see what it is. */
// Something with the name .snownews exists, let's see what it is.
if ((dirtest.st_mode & S_IFDIR) != S_IFDIR) {
MainQuit ("Creating config directory ~/.snownews/",
"A file with the name \"~/.snownews/\" exists!");
@ -564,7 +564,7 @@ int Config (void) {
snprintf (file, sizeof(file), "%s/.snownews/cache", getenv("HOME"));
if ((stat (file, &dirtest)) == -1) {
/* Create directory. */
// Create directory.
if (mkdir (file, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0)
MainQuit (_("Creating config directory ~/.snownews/cache/"), strerror(errno));
} else {
@ -574,8 +574,8 @@ int Config (void) {
}
}
/* Redirect stderr to ~/.snownews/error.log
Be sure to call _after_ the directory checks above! */
// Redirect stderr to ~/.snownews/error.log
// Be sure to call _after_ the directory checks above!
snprintf (file, sizeof(file), "%s/.snownews/error.log", getenv("HOME"));
errorlog = fopen (file, "w+");
dup2 (fileno(errorlog), STDERR_FILENO);
@ -585,9 +585,9 @@ int Config (void) {
snprintf (file, sizeof(file), "%s/.snownews/browser", getenv("HOME"));
SetupBrowser (file);
/*************
* Feed list *
*************/
//------------
// Feed list
//------------
snprintf (file, sizeof(file), "%s/.snownews/urls", getenv("HOME"));
configfile = fopen (file, "r");
@ -595,7 +595,7 @@ int Config (void) {
UIStatus (_("Creating new configfile."), 0, 0);
configfile = fopen (file, "w+");
if (configfile == NULL)
MainQuit (_("Create initial configfile \"urls\""), strerror(errno)); /* Still didn't work? */
MainQuit (_("Create initial configfile \"urls\""), strerror(errno)); // Still didn't work?
} else {
while (!feof(configfile)) {
if ((fgets (filebuf, sizeof(filebuf), configfile)) == NULL)
@ -606,20 +606,20 @@ int Config (void) {
numfeeds++;
new_ptr = newFeedStruct();
/* Reset to NULL on every loop run! */
// Reset to NULL on every loop run!
categories = NULL;
/* File format is url|custom name|comma seperated categories */
// File format is url|custom name|comma seperated categories
tmpbuf = strdup (filebuf);
/* Munch trailing newline. */
// Munch trailing newline.
if (tmpbuf[strlen(tmpbuf)-1] == '\n')
tmpbuf[strlen(tmpbuf)-1] = '\0';
freeme = tmpbuf;
tmpstr = strsep (&tmpbuf, "|");
/* The first | was squished with \0 so we can strdup the first part. */
// The first | was squished with \0 so we can strdup the first part.
new_ptr->feedurl = strdup (freeme);
if (strncasecmp (new_ptr->feedurl, "exec:", 5) == 0) {
@ -628,7 +628,7 @@ int Config (void) {
new_ptr->smartfeed = 1;
}
/* Save start position of override string */
// Save start position of override string
tmpstr = strsep (&tmpbuf, "|");
if (tmpstr != NULL) {
if (*tmpstr != '\0')
@ -646,10 +646,10 @@ int Config (void) {
new_ptr->perfeedfilter = strdup (tmpstr);
}
/* We don't need freeme anymore. */
// We don't need freeme anymore.
free (freeme);
/* Put categories into cat struct. */
// Put categories into cat struct.
if (categories != NULL) {
freeme = categories;
@ -664,12 +664,12 @@ int Config (void) {
} else
new_ptr->feedcategories = NULL;
/* Load cookies for this feed.
But skip loading cookies for execurls. */
// Load cookies for this feed.
// But skip loading cookies for execurls.
if (new_ptr->execurl != 1)
LoadCookies (new_ptr);
/* Add to bottom of pointer chain. */
// Add to bottom of pointer chain.
new_ptr->next_ptr = NULL;
if (first_ptr == NULL) {
new_ptr->prev_ptr = NULL;

View File

@ -28,7 +28,7 @@ int easterEgg (void) {
char file[256];
struct stat filetest;
/* Get current time. */
// Get current time.
tunix = time(0);
t = localtime(&tunix);

View File

@ -30,21 +30,21 @@ extern struct color color;
extern char *browser;
extern int cursor_always_visible;
/* Init the ncurses library. */
// Init the ncurses library.
void InitCurses (void) {
initscr();
keypad (stdscr, TRUE); /* Activate keypad so we can read function keys with getch. */
keypad (stdscr, TRUE); // Activate keypad so we can read function keys with getch.
cbreak(); /* No buffering. */
noecho(); /* Do not echo typed chars onto the screen. */
cbreak(); // No buffering.
noecho(); // Do not echo typed chars onto the screen.
clear();
if (!cursor_always_visible)
curs_set(0); /* Hide cursor. */
curs_set(0); // Hide cursor.
refresh();
}
/* Print text in statusbar. */
// Print text in statusbar.
void UIStatus (const char * text, int delay, int warning) {
if (warning)
attron (COLOR_PAIR(10));
@ -53,8 +53,8 @@ void UIStatus (const char * text, int delay, int warning) {
attron (WA_REVERSE);
mvaddnstr (LINES-1, 1, text, COLS-2);
/* attroff is called here. If the calling function had it switched on,
switch it on again there! */
// attroff is called here. If the calling function had it switched on,
// switch it on again there!
if (warning)
attroff (COLOR_PAIR(10));
attroff (WA_REVERSE);
@ -65,8 +65,8 @@ void UIStatus (const char * text, int delay, int warning) {
sleep (delay);
}
/* Swap all pointers inside a feed struct.
Should only swap next and prev pointers of two structs! */
// Swap all pointers inside a feed struct.
// Should only swap next and prev pointers of two structs!
void SwapPointers (struct feed * one, struct feed * two) {
struct feed *tmp;
@ -138,7 +138,7 @@ void SwapPointers (struct feed * one, struct feed * two) {
free (tmp);
}
/* Ignore "A", "The", etc. prefixes when sorting feeds. */
// Ignore "A", "The", etc. prefixes when sorting feeds.
const char * SnowSortIgnore (const char * title) {
if (strncasecmp (title, "a ", 2) == 0)
return title+2;
@ -148,15 +148,15 @@ const char * SnowSortIgnore (const char * title) {
return title;
}
/* Sort the struct list alphabetically.
Sorting criteria is struct feed->title */
// Sort the struct list alphabetically.
// Sorting criteria is struct feed->title
void SnowSort (void) {
int elements = 0;
int i;
const char *one, *two;
struct feed * cur_ptr;
/* If there is no element do not run sort or it'll crash! */
// If there is no element do not run sort or it'll crash!
if (first_ptr == NULL)
return;
@ -176,14 +176,14 @@ void SnowSort (void) {
}
}
/* Draw a box with WA_REVERSE at coordinates x1y1/x2y2 */
// Draw a box with WA_REVERSE at coordinates x1y1/x2y2
void UISupportDrawBox (int x1, int y1, int x2, int y2) {
int i, j;
attron (WA_REVERSE);
for (i = y1; i <= y2; i++) {
for (j = x1; j <= x2; j++) {
/* Pretty borders. Well, they just sucked. ;)
// Pretty borders. Well, they just sucked. ;)
if (i == y1) {
if (j == x1)
mvaddch (i, j, ACS_ULCORNER);
@ -201,14 +201,13 @@ void UISupportDrawBox (int x1, int y1, int x2, int y2) {
} else if (j == x1 || j == x2) {
mvaddch (i, j, ACS_VLINE);
} else
*/
mvaddch (i, j, ' ');
}
}
attroff (WA_REVERSE);
}
/* Draw main program header. */
// Draw main program header.
void UISupportDrawHeader (const char * headerstring) {
clearLine (0, INVERSE);
@ -224,27 +223,27 @@ void UISupportDrawHeader (const char * headerstring) {
attroff (WA_REVERSE);
}
/* Take a URL and execute in default browser.
Apply all security restrictions before running system()! */
// Take a URL and execute in default browser.
// Apply all security restrictions before running system()!
void UISupportURLJump (const char * url) {
int len;
char *tmp;
char *escapetext = NULL;
char *syscall = NULL;
/* Should not happen. Nope, really should not happen. */
// Should not happen. Nope, really should not happen.
if (url == NULL)
return;
/* Smartfeeds cannot be opened (for now). */
// Smartfeeds cannot be opened (for now).
if (strncmp(url, "smartfeed", 9) == 0)
return;
/* Complain loudly if browser string contains a single quote. */
// Complain loudly if browser string contains a single quote.
if (strstr(browser, "'") != NULL)
UIStatus (_("Unsafe browser string (contains quotes)! See snownews.kcore.de/faq#toc2.4"), 5, 1);
/* Discard url if it contains a single quote! */
// Discard url if it contains a single quote!
if ((strstr(url, "'")) == NULL) {
len = strlen(url) + 3;
escapetext = malloc (len);
@ -269,7 +268,7 @@ void UISupportURLJump (const char * url) {
tmp = malloc (len);
snprintf (tmp, len, "%s 2>/dev/null", syscall);
/* Switch on the cursor. */
// Switch on the cursor.
curs_set(1);
endwin();
@ -278,7 +277,7 @@ void UISupportURLJump (const char * url) {
InitCurses();
/* Hide cursor again. */
// Hide cursor again.
if (!cursor_always_visible)
curs_set(0);
@ -289,7 +288,7 @@ void UISupportURLJump (const char * url) {
void SmartFeedsUpdate (void) {
struct feed *cur_ptr;
/* Find our smart feed. */
// Find our smart feed.
for (cur_ptr = first_ptr; cur_ptr != NULL; cur_ptr = cur_ptr->next_ptr) {
if (cur_ptr->smartfeed == 1)
SmartFeedNewitems (cur_ptr);
@ -301,9 +300,9 @@ void SmartFeedNewitems (struct feed * smart_feed) {
struct newsitem *new_item;
struct newsitem *cur_item;
/* Be smart and don't leak the smart feed.
The items->data structures must not be freed, since a smart feed is only
a pointer collection and does not contain allocated memory. */
// Be smart and don't leak the smart feed.
// The items->data structures must not be freed, since a smart feed is only
// a pointer collection and does not contain allocated memory.
if (smart_feed->items != NULL) {
while (smart_feed->items->next_ptr != NULL) {
smart_feed->items = smart_feed->items->next_ptr;
@ -312,19 +311,19 @@ void SmartFeedNewitems (struct feed * smart_feed) {
free (smart_feed->items);
}
/* This must be NULL if there are no items. */
// This must be NULL if there are no items.
smart_feed->items = NULL;
for (cur_feed = first_ptr; cur_feed != NULL; cur_feed = cur_feed->next_ptr) {
/* Do not add the smart feed recursively. 8) */
// Do not add the smart feed recursively. 8)
if (cur_feed != smart_feed) {
for (cur_item = cur_feed->items; cur_item != NULL; cur_item = cur_item->next_ptr) {
/* If item is unread, add to smart feed. */
// If item is unread, add to smart feed.
if (cur_item->data->readstatus == 0) {
new_item = malloc (sizeof (struct newsitem));
new_item->data = cur_item->data;
/* Add to data structure. */
// Add to data structure.
new_item->next_ptr = NULL;
if (smart_feed->items == NULL) {
new_item->prev_ptr = NULL;
@ -340,7 +339,7 @@ void SmartFeedNewitems (struct feed * smart_feed) {
}
}
/* Only fill out once. */
// Only fill out once.
if (smart_feed->title == NULL)
smart_feed->title = strdup (_("(New headlines)"));
if (smart_feed->link == NULL)
@ -350,7 +349,7 @@ void SmartFeedNewitems (struct feed * smart_feed) {
int SmartFeedExists (const char * smartfeed) {
struct feed *cur_ptr;
/* Find our smart feed. */
// Find our smart feed.
for (cur_ptr = first_ptr; cur_ptr != NULL; cur_ptr = cur_ptr->next_ptr) {
if (strcmp(smartfeed, "newitems") == 0) {
if (cur_ptr->smartfeed == 1)
@ -378,7 +377,7 @@ void displayErrorLog (void) {
char *pager = NULL;
char *env;
/* Get the user's pager or default to less. */
// Get the user's pager or default to less.
env = getenv("PAGER");
if (env)
pager = strdup(env);
@ -390,7 +389,7 @@ void displayErrorLog (void) {
snprintf (command, sizeof(command), "%s %s", pager, errorlog);
/* Call as few as possible functions once we've left ncurses. */
// Call as few as possible functions once we've left ncurses.
endwin();
system(command);
InitCurses();

View File

@ -30,7 +30,7 @@ void AutoVersionCheck (void) {
struct feed *update;
FILE *lastupdated;
char file[512];
char timestring[21]; /* Should be enough for 64bit systems. */
char timestring[21]; // Should be enough for 64bit systems.
char oldtimestring[21];
int oldtime;
char *versionstring = NULL;
@ -38,7 +38,7 @@ void AutoVersionCheck (void) {
update = newFeedStruct();
/* We check once a week. */
// We check once a week.
snprintf (timestring, sizeof(timestring), "%d", (int) time(NULL));
snprintf (file, sizeof(file), "%s/.snownews/updatecheck", getenv("HOME"));
lastupdated = fopen (file, "r+");
@ -50,10 +50,10 @@ void AutoVersionCheck (void) {
fgets (oldtimestring, sizeof(oldtimestring), lastupdated);
oldtime = atoi(oldtimestring);
/* If -1 is given in updatecheck or last check is <1 week, skip the check. */
// If -1 is given in updatecheck or last check is <1 week, skip the check.
if (((((int) time(NULL))-oldtime) < 604800) ||
(oldtime == -1)) {
/* Less than one week. */
// Less than one week.
fclose (lastupdated);
free (update);
return;

View File

@ -29,13 +29,13 @@ struct newsitem *firstcopy;
static xmlChar const * const dcNs = (unsigned char *)"http://purl.org/dc/elements/1.1/";
static xmlChar const * const snowNs = (unsigned char *)"http://snownews.kcore.de/ns/1.0/";
/* Wird während des Parsens aufgerufen, falls wir auf ein <channel> Element
treffen. Die Funktion gibt ein neues Struct für den Newsfeed zurück. */
// Called during parsing, if we look for a <channel> element
// The function returns a new struct for the newsfeed.
void parse_rdf10_channel(struct feed * feed, xmlDocPtr doc, xmlNodePtr node) {
xmlNodePtr cur;
/* Free everything before we write to it again. */
// Free everything before we write to it again.
free (feed->title);
free (feed->link);
free (feed->description);
@ -58,20 +58,20 @@ void parse_rdf10_channel(struct feed * feed, xmlDocPtr doc, xmlNodePtr node) {
free (feed->items);
}
/* Im Augenblick haben wir noch keine Items, also die Liste auf NULL setzen. */
// At the moment we have no items, so set the list to zero.
feed->items = NULL;
feed->title = NULL;
feed->link= NULL;
feed->description = NULL;
/* Alle Tags im <channel> Tag durchgehen und die Informationen extrahieren */
// Go through all the tags in the <channel> tag and extract the information
for (cur = node; cur != NULL; cur = cur->next) {
if (cur->type != XML_ELEMENT_NODE)
continue;
if (xmlStrcmp(cur->name, (unsigned char *)"title") == 0) {
feed->title = (char *)xmlNodeListGetString(doc, cur->children, 1);
CleanupString (feed->title, 1);
/* Remove trailing newline */
// Remove trailing newline
if (feed->title != NULL) {
if (strlen(feed->title) > 1) {
if (feed->title[strlen(feed->title)-1] == '\n')
@ -81,7 +81,7 @@ void parse_rdf10_channel(struct feed * feed, xmlDocPtr doc, xmlNodePtr node) {
}
else if (xmlStrcmp(cur->name, (unsigned char *)"link") == 0) {
feed->link = (char *)xmlNodeListGetString(doc, cur->children, 1);
/* Remove trailing newline */
// Remove trailing newline
if (feed->link != NULL) {
if (strlen(feed->link) > 1) {
if (feed->link[strlen(feed->link)-1] == '\n')
@ -101,7 +101,7 @@ void parse_rdf20_channel(struct feed * feed, xmlDocPtr doc, xmlNodePtr node)
{
xmlNodePtr cur;
/* Free everything before we write to it again. */
// Free everything before we write to it again.
free (feed->title);
free (feed->link);
free (feed->description);
@ -124,20 +124,20 @@ void parse_rdf20_channel(struct feed * feed, xmlDocPtr doc, xmlNodePtr node)
free (feed->items);
}
/* Im Augenblick haben wir noch keine Items, also die Liste auf NULL setzen. */
// At the moment we have no items, so set the list to zero.
feed->items = NULL;
feed->title = NULL;
feed->link = NULL;
feed->description = NULL;
/* Alle Tags im <channel> Tag durchgehen und die Informationen extrahieren */
// Go through all the tags in the <channel> tag and extract the information
for (cur = node; cur != NULL; cur = cur->next) {
if (cur->type != XML_ELEMENT_NODE)
continue;
if (xmlStrcmp(cur->name, (unsigned char *)"title") == 0) {
feed->title = (char *)xmlNodeListGetString(doc, cur->children, 1);
CleanupString (feed->title, 1);
/* Remove trailing newline */
// Remove trailing newline
if (feed->title != NULL) {
if (strlen(feed->title) > 1) {
if (feed->title[strlen(feed->title)-1] == '\n')
@ -147,7 +147,7 @@ void parse_rdf20_channel(struct feed * feed, xmlDocPtr doc, xmlNodePtr node)
}
else if (xmlStrcmp(cur->name, (unsigned char *)"link") == 0) {
feed->link = (char *)xmlNodeListGetString(doc, cur->children, 1);
/* Remove trailing newline */
// Remove trailing newline
if (feed->link != NULL) {
if (strlen(feed->link) > 1) {
if (feed->link[strlen(feed->link)-1] == '\n')
@ -164,10 +164,10 @@ void parse_rdf20_channel(struct feed * feed, xmlDocPtr doc, xmlNodePtr node)
}
}
/* Diese Funktion wird jedes Mal aufgerufen, wenn wir auf ein <item> treffen.
Als Parameter benötigt sie den aktuellen Newsfeed (struct newsfeed *),
sowie das aktuelle XML Document-Handle und das aktuelle Element, beide
kommen direkt von der libxml. */
// This function is called every time we hit an <item>. As parameter it
// needs the current newsfeed (struct newsfeed *), as well as the current
// XML Document handle and the current element, both come directly from
// the libxml.
void parse_rdf10_item(struct feed *feed, xmlDocPtr doc, xmlNodePtr node)
{
@ -178,7 +178,7 @@ void parse_rdf10_item(struct feed *feed, xmlDocPtr doc, xmlNodePtr node)
struct newsitem *item;
struct newsitem *current;
/* Speicher für ein neues Newsitem reservieren */
// Reserve memory for a new news item
item = malloc(sizeof (struct newsitem));
item->data = malloc (sizeof (struct newsdata));
@ -190,62 +190,62 @@ void parse_rdf10_item(struct feed *feed, xmlDocPtr doc, xmlNodePtr node)
item->data->parent = feed;
item->data->date = 0;
/* Alle Tags im <item> Tag durchgehen und die Informationen extrahieren.
Selbe Vorgehensweise wie in der parse_channel() Funktion */
// Go through all the tags in the <item> tag and extract the information.
// same procedure as in the parse_channel () function
for (cur = node; cur != NULL; cur = cur->next) {
if (cur->type != XML_ELEMENT_NODE)
continue;
/* Basic RSS */
/* Title */
// Basic RSS
// Title
if (xmlStrcmp(cur->name, (unsigned char *)"title") == 0) {
item->data->title = (char *)xmlNodeListGetString(doc, cur->children, 1);
CleanupString (item->data->title, 1);
/* Remove trailing newline */
// Remove trailing newline
if (item->data->title != NULL) {
if (strlen(item->data->title) > 1) {
if (item->data->title[strlen(item->data->title)-1] == '\n')
item->data->title[strlen(item->data->title)-1] = '\0';
}
}
/* link */
// link
} else if (xmlStrcmp(cur->name, (unsigned char *)"link") == 0) {
item->data->link = (char *)xmlNodeListGetString(doc, cur->children, 1);
/* Remove trailing newline */
// Remove trailing newline
if (item->data->link != NULL) {
if (strlen(item->data->link) > 1) {
if (item->data->link[strlen(item->data->link)-1] == '\n')
item->data->link[strlen(item->data->link)-1] = '\0';
}
}
/* Description */
// Description
} else if (xmlStrcmp(cur->name, (unsigned char *)"description") == 0) {
item->data->description = (char *)xmlNodeListGetString(doc, cur->children, 1);
CleanupString (item->data->description, 0);
/* Userland extensions (No namespace!)*/
/* guid */
// Userland extensions (No namespace!)
// guid
} else if (xmlStrcmp(cur->name, (unsigned char *)"guid") == 0) {
guid = (char *)xmlNodeListGetString(doc, cur->children, 1);
/* pubDate */
// pubDate
} else if (xmlStrcmp(cur->name, (unsigned char *)"pubDate") == 0) {
date_str = (char *)xmlNodeListGetString(doc, cur->children, 1);
item->data->date = pubDateToUnix(date_str);
xmlFree (date_str);
/* Dublin Core */
/* dc:date */
// Dublin Core
// dc:date
} else if (cur->ns &&
(xmlStrcmp(cur->ns->href, dcNs) == 0) &&
(xmlStrcmp(cur->name, (unsigned char *)"date") == 0)) {
date_str = (char *)xmlNodeListGetString(doc, cur->children, 1);
item->data->date = ISODateToUnix(date_str);
xmlFree (date_str);
/* Internal usage */
/* Obsolete/backware compat/migration code */
// Internal usage
// Obsolete/backware compat/migration code
} else if (xmlStrcmp(cur->name, (unsigned char *)"readstatus") == 0) {
/* Will cause memory leak otherwise, xmlNodeListGetString must be freed. */
// Will cause memory leak otherwise, xmlNodeListGetString must be freed.
readstatusstring = xmlNodeListGetString(doc, cur->children, 1);
item->data->readstatus = atoi ((char *)readstatusstring);
xmlFree (readstatusstring);
/* Using snow namespace */
// Using snow namespace
} else if (cur->ns && (xmlStrcmp(cur->ns->href, snowNs) == 0) &&
(xmlStrcmp(cur->name, (unsigned char *)"readstatus") == 0)) {
readstatusstring = xmlNodeListGetString(doc, cur->children, 1);
@ -262,16 +262,16 @@ void parse_rdf10_item(struct feed *feed, xmlDocPtr doc, xmlNodePtr node)
}
}
/* If we have loaded the hash from disk cache, don't regenerate it.
<guid> is not saved in the cache, thus we would generate a different
hash than the one from the live feed. */
// If we have loaded the hash from disk cache, don't regenerate it.
// <guid> is not saved in the cache, thus we would generate a different
// hash than the one from the live feed.
if (item->data->hash == NULL) {
const char* hashitems[] = { item->data->title, item->data->link, guid, NULL };
item->data->hash = genItemHash (hashitems, 3);
xmlFree (guid);
}
/* If saverestore == 1, restore readstatus. */
// If saverestore == 1, restore readstatus.
if (saverestore == 1) {
for (current = firstcopy; current != NULL; current = current->next_ptr) {
if (strcmp(item->data->hash, current->data->hash) == 0) {
@ -294,7 +294,7 @@ void parse_rdf10_item(struct feed *feed, xmlDocPtr doc, xmlNodePtr node)
}
/* rrr */
// rrr
int DeXML (struct feed * cur_ptr) {
xmlDocPtr doc;
@ -306,14 +306,13 @@ int DeXML (struct feed * cur_ptr) {
return -1;
saverestore = 0;
/* Wenn cur_ptr->items != NULL dann können wir uns item->readstatus
zwischenspeichern. */
// If cur_ptr-> items! = NULL then we can cache item->readstatus
if (cur_ptr->items != NULL) {
saverestore = 1;
firstcopy = NULL;
/* Copy current newsitem struct. */
// Copy current newsitem struct. */
for (cur_item = cur_ptr->items; cur_item != NULL; cur_item = cur_item->next_ptr) {
copy = malloc (sizeof(struct newsitem));
copy->data = malloc (sizeof (struct newsdata));
@ -338,17 +337,17 @@ int DeXML (struct feed * cur_ptr) {
}
}
/* xmlRecoverMemory:
parse an XML in-memory document and build a tree.
In case the document is not Well Formed, a tree is built anyway. */
// xmlRecoverMemory:
// parse an XML in-memory document and build a tree.
// In case the document is not Well Formed, a tree is built anyway.
doc = xmlRecoverMemory(cur_ptr->feed, strlen(cur_ptr->feed));
if (doc == NULL)
return 2;
/* Das Root-Element finden (in unserem Fall sollte es "<RDF:RDF>" heißen.
Dabei wird das RDF: Prefix fürs Erste ignoriert, bis der Jaguar
herausfindet, wie man das genau auslesen kann (jau). */
// Find the root element (in our case, it should read "<RDF: RDF>").
// The RDF: prefix is ignored for now until the Jaguar
// Find out how to read that exactly (jau).
cur = xmlDocGetRootElement(doc);
if (cur == NULL) {
@ -356,14 +355,12 @@ int DeXML (struct feed * cur_ptr) {
return 2;
}
/* Überprüfen, ob das Element auch wirklich <RDF> heißt */
// Check if the element really is called <RDF>
if (xmlStrcmp(cur->name, (unsigned char *)"RDF") == 0) {
/* Jetzt gehen wir alle Elemente im Dokument durch. Diese Schleife
selbst läuft jedoch nur durch die Elemente auf höchster Ebene
(bei HTML wären das nur HEAD und BODY), wandert also nicht die
gesamte Struktur nach unten durch. Dafür sind die Funktionen zuständig,
die wir dann in der Schleife selbst aufrufen. */
// Now we go through all the elements in the document. This loop however,
// only the highest level elements work (HTML would only be HEAD and
// BODY), so do not wander entire structure down through. The functions
// are responsible for this, which we then call in the loop itself.
for (cur = cur->children; cur != NULL; cur = cur->next) {
if (cur->type != XML_ELEMENT_NODE)
continue;
@ -371,7 +368,7 @@ int DeXML (struct feed * cur_ptr) {
parse_rdf10_channel(cur_ptr, doc, cur->children);
if (xmlStrcmp(cur->name, (unsigned char *)"item") == 0)
parse_rdf10_item(cur_ptr, doc, cur->children);
/* Last-Modified is only used when reading from internal feeds (disk cache). */
// Last-Modified is only used when reading from internal feeds (disk cache).
if (cur->ns && (xmlStrcmp(cur->ns->href, snowNs) == 0) &&
(xmlStrcmp(cur->name, (unsigned char *)"lastmodified") == 0))
cur_ptr->lastmodified = (char *)xmlNodeListGetString(doc, cur->children, 1);
@ -391,7 +388,7 @@ int DeXML (struct feed * cur_ptr) {
xmlFreeDoc(doc);
if (saverestore == 1) {
/* free struct newsitem *copy. */
// free struct newsitem *copy.
while (firstcopy->next_ptr != NULL) {
firstcopy = firstcopy->next_ptr;
free (firstcopy->prev_ptr->data->hash);
@ -406,7 +403,7 @@ int DeXML (struct feed * cur_ptr) {
if (cur_ptr->original != NULL)
free (cur_ptr->original);
/* Set -> title to something if it's a NULL pointer to avoid crash with strdup below. */
// Set -> title to something if it's a NULL pointer to avoid crash with strdup below.
if (cur_ptr->title == NULL)
cur_ptr->title = strdup (cur_ptr->feedurl);
converted = iconvert (cur_ptr->title);
@ -416,7 +413,7 @@ int DeXML (struct feed * cur_ptr) {
}
cur_ptr->original = strdup (cur_ptr->title);
/* Restore custom title. */
// Restore custom title.
if (cur_ptr->override != NULL) {
free (cur_ptr->title);
cur_ptr->title = strdup (cur_ptr->override);

View File

@ -48,7 +48,7 @@ int jg_zlib_uncompress(void const *in_buf, int in_size,
int result;
int new_bytes;
/* Prepare the stream structure. */
// Prepare the stream structure.
stream.zalloc = NULL;
stream.zfree = NULL;
stream.opaque = NULL;
@ -61,7 +61,7 @@ int jg_zlib_uncompress(void const *in_buf, int in_size,
*out_size = 0;
if (gzip)
result = inflateInit2(&stream, MAX_WBITS + 32); /* UNTESTED */
result = inflateInit2(&stream, MAX_WBITS + 32); // UNTESTED
else
result = inflateInit2(&stream, -MAX_WBITS);
@ -72,13 +72,13 @@ int jg_zlib_uncompress(void const *in_buf, int in_size,
}
do {
/* Should be Z_FINISH? */
// Should be Z_FINISH?
result = inflate(&stream, Z_NO_FLUSH);
switch (result) {
case Z_BUF_ERROR:
if (stream.avail_in == 0)
goto DONE; /* zlib bug */
/* fallthrough */
goto DONE; // zlib bug
// fallthrough
case Z_ERRNO:
case Z_NEED_DICT:
case Z_MEM_ERROR:
@ -93,7 +93,7 @@ int jg_zlib_uncompress(void const *in_buf, int in_size,
return JG_ZLIB_ERROR_UNCOMPRESS;
}
if (stream.avail_out < sizeof tmp_buf) {
/* Add the new uncompressed data to our output buffer. */
// Add the new uncompressed data to our output buffer.
new_bytes = sizeof tmp_buf - stream.avail_out;
out_buf = realloc(out_buf, out_buf_bytes + new_bytes);
memcpy(out_buf + out_buf_bytes, tmp_buf, new_bytes);
@ -101,7 +101,7 @@ int jg_zlib_uncompress(void const *in_buf, int in_size,
stream.next_out = tmp_buf;
stream.avail_out = sizeof tmp_buf;
} else {
/* For some reason, inflate() didn't write out a single byte. */
// For some reason, inflate() didn't write out a single byte.
inflateEnd(&stream);
free(out_buf);
if (JG_ZLIB_DEBUG)
@ -114,11 +114,11 @@ DONE:
inflateEnd(&stream);
/* Null-terminate the output buffer so it can be handled like a string. */
// Null-terminate the output buffer so it can be handled like a string.
out_buf = realloc(out_buf, out_buf_bytes + 1);
out_buf[out_buf_bytes] = 0;
/* The returned size does NOT include the additionall null byte! */
// The returned size does NOT include the additionall null byte!
if (out_size != NULL)
*out_size = out_buf_bytes;
@ -127,10 +127,8 @@ DONE:
return 0;
}
/* Decompressed gzip,deflate compressed data. This is what the webservers usually send. */
int jg_gzip_uncompress(void const *in_buf, int in_size,
void **out_buf_ptr, int *out_size)
// Decompressed gzip,deflate compressed data. This is what the webservers usually send.
int jg_gzip_uncompress(void const *in_buf, int in_size, void **out_buf_ptr, int *out_size)
{
char tmpstring[1024];
struct gzip_header const *header;
@ -163,7 +161,7 @@ int jg_gzip_uncompress(void const *in_buf, int in_size,
}
if (header->flags & 8) {
/* skip the file name */
// skip the file name
while (offset < in_size) {
if (((char *)in_buf)[offset] == 0) {
offset++;
@ -175,6 +173,5 @@ int jg_gzip_uncompress(void const *in_buf, int in_size,
data_start = (char *)in_buf + offset;
return jg_zlib_uncompress(data_start, in_size - offset - 8,
out_buf_ptr, out_size, 0);
return jg_zlib_uncompress(data_start, in_size - offset - 8, out_buf_ptr, out_size, 0);
}