Use libcurl to download feeds

Replace the custom HTTP client with a libcurl dependency. This
considerably increases snownews capabilities. Most importantly,
https feeds are now supported without using external downloaders.

A lot of code supporting the old HTTP client became obsolete
and was removed, including the direct zlib dependency.
This commit is contained in:
Mike Sharov 2021-04-10 18:43:09 -04:00
parent 48b6eb9630
commit fe24fb933e
20 changed files with 86 additions and 1550 deletions

View File

@ -2,7 +2,7 @@ Snownews
========
Snownews is a command-line RSS feed reader, originally written by
[Oliver Feiler](https://github.com/kouya) (#kouya).
[Oliver Feiler](https://github.com/kouya) (@kouya).
It is designed to be simple and lightweight, and integrates well with
other command-line tools, for both generating and filtering the feeds
it reads.
@ -12,14 +12,11 @@ Features
* Runs on Linux, BSD, OS X (Darwin), Solaris and probably many more Unices. Yes, even works under Cygwin.
* Fast and very resource friendly.
* Builtin HTTP client will follow server redirects and update feed URLs that point to permanent redirects (301) automatically.
* Understands "Not-Modified" (304) server replies and handles gzip compression.
* Downloads feeds using libcurl to support a variety of URL types.
* Uses local cache for minimal network traffic.
* Supports HTTP proxy.
* Supports HTTP authentication (basic and digest methods).
* Supports cookies.
* A help menu available throughout the program.
* Few dependencies on external libraries; ncurses and libxml2.
* Few dependencies on external libraries; ncurses, libcurl, and libxml2.
* Import feature for OPML subscription lists.
* Fully customizable key bindings of all program functions.
* Type Ahead Find for quick and easy navigation.
@ -33,9 +30,9 @@ You will need the following:
- GCC compiler 5+
- ncurses 5.0+
- libcurl
- libxml2
- Perl (for extension scripts)
- gettext (lib and msgfmt tool)
- gettext
Once you have the above dependencies installed:
@ -44,19 +41,11 @@ Once you have the above dependencies installed:
make install
```
By default, this will install Snownews into ``/usr/local``. If you
prefer it to go somewhere else, set the ``./configure --prefix=DIR``
parameter. ``configure --help`` will list other options that you may
By default, this will install Snownews into `/usr/local`. If you
prefer it to go somewhere else, set the `./configure --prefix=DIR`
parameter. `configure --help` will list other options that you may
find interesting.
How to use it
---------------
Snownews comes with a complete man page, where you can find all
the details for its use. If you prefer a tutorial, you can find one
[here](https://retro-freedom.nz/tech-101-snownews.html). The man page
is available in English, German, Dutch and French at the moment.
Localization
------------
@ -84,6 +73,5 @@ If you want to create a new translation or update an exisiting one, send a patch
License
-------
Snownews is licensed under the GNU General Public License, version 3 *only*
(SPDX code ``GPL-3.0``). For more details, as well as the text of the license,
please see the ``LICENSE.md`` file.
Snownews is licensed under the GNU General Public License, version 3 only.
For more details, see the text of the license in `LICENSE.md`.

View File

@ -19,7 +19,6 @@
#include "about.h"
#include <ncurses.h>
#include <sys/time.h>
#include <sys/stat.h>
//----------------------------------------------------------------------

View File

@ -64,6 +64,11 @@
#include <limits.h>
#include <locale.h>
#include <assert.h>
#include <syslog.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/stat.h>
#include <stdio.h>
#include <time.h>
#include "os-support.h"

4
configure vendored
View File

@ -34,9 +34,9 @@ seds=[s/^#undef \(USE_UNSUPPORTED_AND_BROKEN_CODE\)/#define \1/]
progs="CC=gcc CC=clang CC=cc INSTALL=install MSGFMT=msgfmt"
# Libs found using pkg-config
pkgs="libxml-2.0 ncurses zlib"
pkgs="libcurl libxml-2.0 ncurses"
# Default pkg flags to substitute when pkg-config is not found
pkg_libs="-lxml2 -lncursesw -lz"
pkg_libs="-lcurl -lxml2 -lncursesw"
pkg_cflags="-I\/usr\/include\/libxml2"
pkg_ldflags=""

182
cookies.c
View File

@ -1,182 +0,0 @@
// This file is part of Snownews - A lightweight console RSS newsreader
//
// Copyright (c) 2003-2004 Oliver Feiler <kiza@kcore.de>
//
// Snownews is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3
// as published by the Free Software Foundation.
//
// Snownews is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with 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
#include "config.h"
#include "ui-support.h"
static void CookieCutter (struct feed* cur_ptr, FILE * cookies)
{
int len = 0;
int cookienr = 0;
// Get current time.
time_t tunix = time (NULL);
char* url = strdup (cur_ptr->feedurl);
char* freeme = url;
strsep (&url, "/");
strsep (&url, "/");
char* tmphost = url;
strsep (&url, "/");
if (url == NULL) {
free (freeme);
return;
}
// If tmphost contains an '@' strip authinfo off url.
if (strchr (tmphost, '@'))
strsep (&tmphost, "@");
char* host = strdup (tmphost); // Current feed hostname.
--url;
url[0] = '/';
if (url[strlen (url) - 1] == '\n')
url[strlen (url) - 1] = '\0';
char* path = strdup (url); // Current feed path.
free (freeme);
freeme = NULL;
while (!feof (cookies)) {
char buf[BUFSIZ]; // File read buffer.
if ((fgets (buf, sizeof (buf), cookies)) == NULL)
break;
// 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.
if (buf[0] == '#')
continue;
char* cookie = strdup (buf);
freeme = cookie;
// Munch trailing newline.
if (cookie[strlen (cookie) - 1] == '\n')
cookie[strlen (cookie) - 1] = '\0';
// Decode the cookie string.
char* cookiehost = NULL;
char* cookiepath = NULL;
char* cookiename = NULL;
char* cookievalue = NULL;
time_t cookieexpire = 0;
bool cookiesecure = false;
for (unsigned i = 0; i < 7; ++i) {
const char* tmpstr = strsep (&cookie, "\t");
if (!tmpstr)
break;
switch (i) {
case 0:
// Cookie hostname.
cookiehost = strdup (tmpstr);
break;
case 1:
// Discard host match value.
break;
case 2:
// Cookie path.
cookiepath = strdup (tmpstr);
break;
case 3:
// Secure cookie?
if (strcasecmp (tmpstr, "TRUE") == 0)
cookiesecure = true;
break;
case 4:
// Cookie expiration date.
cookieexpire = strtoul (tmpstr, NULL, 10);
break;
case 5:
// NAME
cookiename = strdup (tmpstr);
break;
case 6:
// VALUE
cookievalue = strdup (tmpstr);
break;
}
}
// 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) && strstr (path, cookiepath) && !cookiesecure && cookieexpire > tunix) {
++cookienr;
// 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);
strcpy (cur_ptr->cookies, "Cookie: ");
strcat (cur_ptr->cookies, cookiename);
strcat (cur_ptr->cookies, "=");
strcat (cur_ptr->cookies, cookievalue);
} else {
len += strlen (cookiename) + 1 + strlen (cookievalue) + 3;
cur_ptr->cookies = realloc (cur_ptr->cookies, len);
strcat (cur_ptr->cookies, "; ");
strcat (cur_ptr->cookies, cookiename);
strcat (cur_ptr->cookies, "=");
strcat (cur_ptr->cookies, cookievalue);
}
} else if ((strstr (host, cookiehost) != NULL) && (strstr (path, cookiepath) != NULL) && (cookieexpire < (int) tunix)) { // Cast time_t tunix to int.
// Print cookie expire warning.
char expirebuf[PATH_MAX];
snprintf (expirebuf, sizeof (expirebuf), _("Cookie for %s has expired!"), cookiehost);
UIStatus (expirebuf, 1, 1);
}
free (freeme);
freeme = NULL;
free (cookiehost);
free (cookiepath);
free (cookiename);
free (cookievalue);
}
free (host);
free (path);
free (freeme);
// 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");
}
}
void LoadCookies (struct feed* cur_ptr)
{
char file[PATH_MAX]; // File locations.
snprintf (file, sizeof (file), SNOWNEWS_CONFIG_DIR "cookies", getenv ("HOME"));
FILE* cookies = fopen (file, "r");
if (!cookies) // No cookies to load.
return;
CookieCutter (cur_ptr, cookies);
fclose (cookies);
}

View File

@ -1,19 +0,0 @@
// This file is part of Snownews - A lightweight console RSS newsreader
//
// Copyright (c) 2003-2004 Oliver Feiler <kiza@kcore.de>
//
// Snownews is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3
// as published by the Free Software Foundation.
//
// Snownews is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Snownews. If not, see http://www.gnu.org/licenses/.
#pragma once
void LoadCookies (struct feed* cur_ptr);

View File

@ -23,7 +23,6 @@
#include "ui-support.h"
#include "parsefeed.h"
#include <ncurses.h>
#include <sys/stat.h>
char* UIOneLineEntryField (int x, int y)
{
@ -263,38 +262,6 @@ void FeedInfo (const struct feed* current_feed)
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. :)
if (current_feed->lasthttpstatus != 0) {
size_t len;
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
mvprintw (12, centerx - (COLS / 2 - 7), _("Last webserver status: (%s) %d"), current_feed->content_type, current_feed->lasthttpstatus);
}
switch (current_feed->lasthttpstatus) {
case 200:
case 304:
mvaddstr (12, centerx - (COLS / 2 - 7) + len + 2, ":-)");
break;
case 401:
case 403:
case 500:
case 503:
mvaddstr (12, centerx - (COLS / 2 - 7) + len + 2, ":-P");
break;
case 404:
case 410:
mvaddstr (12, centerx - (COLS / 2 - 7) + len + 2, ":-(");
break;
default:
mvaddstr (12, centerx - (COLS / 2 - 7) + len + 2, "8-X");
break;
}
}
// Display filter script if any.
if (current_feed->perfeedfilter != NULL) {
UISupportDrawBox (5, 13, COLS - 6, 14);

View File

@ -16,9 +16,6 @@
#include "filters.h"
#include "ui-support.h"
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
//----------------------------------------------------------------------
@ -76,6 +73,7 @@ int FilterPipeNG (struct feed* cur_ptr)
free (cur_ptr->xmltext);
cur_ptr->xmltext = NULL;
cur_ptr->content_length = 0;
char* filter = strdup (cur_ptr->perfeedfilter);
char* command = strsep (&filter, " ");

View File

@ -25,7 +25,6 @@
#include "setup.h"
#include "ui-support.h"
#include <ncurses.h>
#include <unistd.h>
#include <libxml/parser.h>
#ifdef UTF_8
#define xmlStrlen(s) xmlUTF8Strlen(s)
@ -819,10 +818,6 @@ void UIMainInterface (void)
new_feed->link = cur_ptr->link;
new_feed->description = cur_ptr->description;
new_feed->lastmodified = cur_ptr->lastmodified;
new_feed->lasthttpstatus = cur_ptr->lasthttpstatus;
new_feed->cookies = cur_ptr->cookies;
new_feed->authinfo = cur_ptr->authinfo;
new_feed->servauth = cur_ptr->servauth;
new_feed->items = cur_ptr->items;
new_feed->problem = cur_ptr->problem;
new_feed->custom_title = cur_ptr->custom_title;
@ -1086,15 +1081,14 @@ void UIMainInterface (void)
}
free (removed->feedurl);
free (removed->xmltext);
removed->xmltext = NULL;
removed->content_length = 0;
free (removed->title);
free (removed->link);
free (removed->description);
free (removed->lastmodified);
free (removed->custom_title);
free (removed->original);
free (removed->cookies);
free (removed->authinfo);
free (removed->servauth);
free (removed);
_feed_list_changed = true;
}

View File

@ -22,115 +22,12 @@
#include "netio.h"
#include "ui-support.h"
#include "parsefeed.h"
#include <errno.h>
#include <ncurses.h>
#include <sys/stat.h>
#include <unistd.h>
#include <libxml/parser.h>
#include <syslog.h>
struct feed* newFeedStruct (void)
{
struct feed* new = calloc (1, sizeof (struct feed));
new->netio_error = NET_ERR_OK;
return new;
}
static void GetHTTPErrorString (char* errorstring, size_t size, unsigned httpstatus)
{
const char* statusmsg = "HTTP %u!";
switch (httpstatus) {
case 400:
statusmsg = "Bad request";
break;
case 402:
statusmsg = "Payment required";
break;
case 403:
statusmsg = "Access denied";
break;
case 500:
statusmsg = "Internal server error";
break;
case 501:
statusmsg = "Not implemented";
break;
case 502:
case 503:
statusmsg = "Service unavailable";
break;
}
snprintf (errorstring, size, statusmsg, httpstatus);
}
static void PrintUpdateError (const struct feed* cur_ptr)
{
enum netio_error err = cur_ptr->netio_error;
char errstr[256];
switch (err) {
case NET_ERR_URL_INVALID:
snprintf (errstr, sizeof (errstr), _("%s: Invalid URL!"), cur_ptr->title);
break;
case NET_ERR_SOCK_ERR:
snprintf (errstr, sizeof (errstr), _("%s: Couldn't create network socket!"), cur_ptr->title);
break;
case NET_ERR_HOST_NOT_FOUND:
snprintf (errstr, sizeof (errstr), _("%s: Can't resolve host!"), cur_ptr->title);
break;
case NET_ERR_CONN_REFUSED:
snprintf (errstr, sizeof (errstr), _("%s: Connection refused!"), cur_ptr->title);
break;
case NET_ERR_CONN_FAILED:
snprintf (errstr, sizeof (errstr), _("%s: Couldn't connect to server: %s"), cur_ptr->title, (strerror (cur_ptr->connectresult) ? strerror (cur_ptr->connectresult) : "(null)"));
break;
case NET_ERR_TIMEOUT:
snprintf (errstr, sizeof (errstr), _("%s: Connection timed out."), cur_ptr->title);
break;
case NET_ERR_UNKNOWN:
break;
case NET_ERR_REDIRECT_COUNT_ERR:
snprintf (errstr, sizeof (errstr), _("%s: Too many HTTP redirects encountered! Giving up."), cur_ptr->title);
break;
case NET_ERR_REDIRECT_ERR:
snprintf (errstr, sizeof (errstr), _("%s: Server sent an invalid redirect!"), cur_ptr->title);
break;
case NET_ERR_HTTP_410:
case NET_ERR_HTTP_404:
snprintf (errstr, sizeof (errstr), _("%s: This feed no longer exists. Please unsubscribe!"), cur_ptr->title);
break;
case NET_ERR_HTTP_NON_200:{
char httperrstr[64];
GetHTTPErrorString (httperrstr, sizeof (httperrstr), cur_ptr->lasthttpstatus);
snprintf (errstr, sizeof (errstr), _("%s: Could not download feed: %s"), cur_ptr->title, httperrstr);
}
break;
case NET_ERR_HTTP_PROTO_ERR:
snprintf (errstr, sizeof (errstr), _("%s: Error in server reply."), cur_ptr->title);
break;
case NET_ERR_AUTH_FAILED:
snprintf (errstr, sizeof (errstr), _("%s: Authentication failed!"), cur_ptr->title);
break;
case NET_ERR_AUTH_NO_AUTHINFO:
snprintf (errstr, sizeof (errstr), _("%s: URL does not contain authentication information!"), cur_ptr->title);
break;
case NET_ERR_AUTH_GEN_AUTH_ERR:
snprintf (errstr, sizeof (errstr), _("%s: Could not generate authentication information!"), cur_ptr->title);
break;
case NET_ERR_AUTH_UNSUPPORTED:
snprintf (errstr, sizeof (errstr), _("%s: Unsupported authentication method requested by server!"), cur_ptr->title);
break;
case NET_ERR_GZIP_ERR:
snprintf (errstr, sizeof (errstr), _("%s: Error decompressing server reply!"), cur_ptr->title);
break;
case NET_ERR_CHUNKED:
snprintf (errstr, sizeof (errstr), _("%s: Error in server reply. Chunked encoding is not supported."), cur_ptr->title);
break;
default:
snprintf (errstr, sizeof (errstr), _("%s: Some error occured for which no specific error message was written."), cur_ptr->title);
break;
}
UIStatus (errstr, 2, 1);
syslog (LOG_ERR, "%s", errstr);
return calloc (1, sizeof (struct feed));
}
// Update given feed from server.
@ -148,13 +45,7 @@ int UpdateFeed (struct feed* cur_ptr)
if (cur_ptr->execurl)
FilterExecURL (cur_ptr);
else {
// Need to work on a copy of ->feedurl, because DownloadFeed() changes the pointer.
char* feedurl = strdup (cur_ptr->feedurl);
free (cur_ptr->xmltext);
cur_ptr->xmltext = DownloadFeed (feedurl, cur_ptr, 0);
free (feedurl);
DownloadFeed (cur_ptr->feedurl, cur_ptr);
// Set title and link structure to something.
// To the feedurl in this case so the program show something
@ -165,11 +56,8 @@ int UpdateFeed (struct feed* cur_ptr)
cur_ptr->link = strdup (cur_ptr->feedurl);
// If the download function returns a NULL pointer return from here.
if (!cur_ptr->xmltext) {
if (cur_ptr->problem)
PrintUpdateError (cur_ptr);
if (!cur_ptr->xmltext)
return 1;
}
}
// Feed downloaded content through the defined filter.
@ -189,6 +77,7 @@ int UpdateFeed (struct feed* cur_ptr)
// We don't need these anymore. Free the raw XML to save some memory.
free (cur_ptr->xmltext);
cur_ptr->xmltext = NULL;
cur_ptr->content_length = 0;
// Mark the time to detect modifications
cur_ptr->mtime = time (NULL);
@ -260,6 +149,7 @@ int LoadFeed (struct feed* cur_ptr)
free (cur_ptr->xmltext);
cur_ptr->xmltext = NULL;
cur_ptr->content_length = 0;
cur_ptr->mtime = cachest.st_mtime;
return 0;
}

3
main.c
View File

@ -20,12 +20,9 @@
#include "io-internal.h"
#include "setup.h"
#include "ui-support.h"
#include <fcntl.h>
#include <ncurses.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
//{{{ Global variables -------------------------------------------------

32
main.h
View File

@ -19,32 +19,6 @@
//----------------------------------------------------------------------
enum netio_error {
NET_ERR_OK,
// Init errors
NET_ERR_URL_INVALID,
// 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
NET_ERR_REDIRECT_COUNT_ERR,
NET_ERR_REDIRECT_ERR,
NET_ERR_HTTP_410,
NET_ERR_HTTP_404,
NET_ERR_HTTP_NON_200,
NET_ERR_HTTP_PROTO_ERR,
NET_ERR_AUTH_FAILED,
NET_ERR_AUTH_NO_AUTHINFO,
NET_ERR_AUTH_GEN_AUTH_ERR,
NET_ERR_AUTH_UNSUPPORTED,
NET_ERR_GZIP_ERR,
NET_ERR_CHUNKED
};
struct feed {
struct newsitem* items;
struct feed* next;
@ -56,17 +30,11 @@ struct feed {
char* description;
char* lastmodified; // Content of header as sent by the server.
char* content_type;
char* cookies; // Login cookies for this feed.
char* authinfo; // HTTP authinfo string.
char* servauth; // Server supplied authorization header.
char* custom_title; // Custom feed title.
char* original; // Original feed title.
char* perfeedfilter; // Pipe feed through this program before parsing.
time_t mtime; // Last modification time
unsigned content_length;
enum netio_error netio_error; // See netio.h
int connectresult; // Socket errno
int lasthttpstatus;
bool problem; // Set if there was a problem downloading the feed.
bool execurl; // Execurl?
bool smartfeed; // 1: new items feed.

View File

@ -1,208 +0,0 @@
// This file is part of Snownews - A lightweight console RSS newsreader
//
// Copyright (c) 2003-2004 Oliver Feiler <kiza@kcore.de>
//
// Snownews is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3
// as published by the Free Software Foundation.
//
// Snownews is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Snownews. If not, see http://www.gnu.org/licenses/.
#include "net-support.h"
#include "conversions.h"
#include "ui-support.h"
#include "digcalc.h"
static char* ConstructBasicAuth (const char* username, const char* password)
{
// Create base64 authinfo.
// RFC 2617. Basic HTTP authentication.
// Authorization: Basic username:password[base64 encoded]
// Construct the cleartext authstring.
char authstring[128];
unsigned len = snprintf (authstring, sizeof (authstring), "%s:%s", username, password);
char* encoded = base64encode (authstring, len);
// "Authorization: Basic " + base64str + \r\n\0
len = 21 + strlen (encoded) + 3;
char* authinfo = malloc (len);
snprintf (authinfo, len, "Authorization: Basic %s\r\n", encoded);
free (encoded);
return authinfo;
}
static char* GetRandomBytes (void)
{
char raw[8];
FILE* devrandom = fopen ("/dev/random", "r");
if (devrandom) {
fread (raw, sizeof (raw), 1, devrandom);
fclose (devrandom);
} else {
for (unsigned i = 0; i < sizeof (raw); ++i)
raw[i] = rand(); // Use rand() if we don't have access to /dev/random.
}
char* randomness = calloc (sizeof (raw) * 2 + 1, 1);
snprintf (randomness, sizeof (raw) * 2 + 1, "%hhx%hhx%hhx%hhx%hhx%hhx%hhx%hhx", raw[0], raw[1], raw[2], raw[3], raw[4], raw[5], raw[6], raw[7]);
return randomness;
}
static char* ConstructDigestAuth (const char* username, const char* password, const char* url, char* authdata)
{
// Variables for the overcomplicated and annoying HTTP digest algo.
char* cnonce = GetRandomBytes();
char* realm = NULL, *qop = NULL, *nonce = NULL, *opaque = NULL;
while (1) {
char* token = strsep (&authdata, ", ");
if (token == NULL)
break;
if (strncasecmp (token, "realm", 5) == 0) {
unsigned len = strlen (token) - 8;
memmove (token, token + 7, len);
token[len] = '\0';
realm = strdup (token);
} else if (strncasecmp (token, "qop", 3) == 0) {
unsigned len = strlen (token) - 6;
memmove (token, token + 5, len);
token[len] = '\0';
qop = strdup (token);
} else if (strncasecmp (token, "nonce", 5) == 0) {
unsigned len = strlen (token) - 8;
memmove (token, token + 7, len);
token[len] = '\0';
nonce = strdup (token);
} else if (strncasecmp (token, "opaque", 6) == 0) {
unsigned len = strlen (token) - 9;
memmove (token, token + 8, len);
token[len] = '\0';
opaque = strdup (token);
}
}
HASHHEX HA1;
DigestCalcHA1 ("md5", username, realm, password, nonce, cnonce, HA1);
static const char szNonceCount[9] = "00000001"; // Can be always 1 if we never use the same cnonce twice.
HASHHEX HA2 = "", Response;
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"
//
unsigned len = 32 + strlen (username) + 10 + strlen (realm) + 10 + strlen (nonce) + 8 + strlen (url) + 28 + strlen (Response) + 16 + strlen (szNonceCount) + 10 + strlen (cnonce) + 4;
if (opaque)
len += 6 + strlen (opaque) + 4;
// Authorization header as sent to the server.
char* authinfo = malloc (len);
snprintf (authinfo, len, "Authorization: Digest username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", algorithm=MD5, response=\"%s\", qop=auth, nc=%s, cnonce=\"%s\"\r\n", username, realm, nonce, url, Response, szNonceCount, cnonce);
free (realm);
free (qop);
free (nonce);
free (cnonce);
if (opaque)
sprintf (authinfo + strlen (authinfo) - strlen ("\r\n"), ", opaque=\"%s\"\r\n", opaque);
free (opaque);
return authinfo;
}
// 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, const char* url, const char* netbuf)
{
// Reset cur_ptr->authinfo.
free (cur_ptr->authinfo);
cur_ptr->authinfo = NULL;
// Catch invalid authdata.
if (!authdata)
return 1;
else if (!strchr (authdata, ':')) // No authinfo found in URL. This should not happen.
return 1;
// Parse username:password
char* username = strdup (authdata);
char* pwtok = username;
strsep (&pwtok, ":");
char* password = strdup (pwtok);
// Extract requested auth type from webserver reply.
char* header = strdup (netbuf);
char* freeme = header;
strsep (&header, " ");
char* authtype = header;
// Catch invalid server replies. authtype should contain at least _something_.
if (!authtype) {
free (freeme);
free (username);
free (password);
return -1;
}
strsep (&header, " ");
// 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.
if (strncasecmp (authtype, "Basic", 5) == 0) // Basic auth.
cur_ptr->authinfo = ConstructBasicAuth (username, password);
else if (strncasecmp (authtype, "Digest", 6) == 0) // Digest auth.
cur_ptr->authinfo = ConstructDigestAuth (username, password, url, header);
else {
// Unkown auth type.
free (freeme);
free (username);
free (password);
return -1;
}
free (username);
free (password);
free (freeme);
if (!cur_ptr->authinfo)
return 2;
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).
//
int checkValidHTTPHeader (const unsigned char* header, unsigned size)
{
unsigned len = strlen ((const char*) header);
if (len > size)
return -1;
for (unsigned i = 0; i < len && header[i] != ':'; ++i)
if ((header[i] < ' ' || header[i] > '~') && header[i] != '\r' && header[i] != '\n')
return -1;
return 0;
}
int checkValidHTTPURL (const unsigned char* url)
{
if (strncasecmp ((const char*) url, "http://", 7) != 0)
return -1;
for (unsigned i = 0, len = strlen ((const char*)url); i < len; ++i)
if (url[i] < ' ' || url[i] > '~')
return -1;
return 0;
}

View File

@ -1,22 +0,0 @@
// This file is part of Snownews - A lightweight console RSS newsreader
//
// Copyright (c) 2003-2004 Oliver Feiler <kiza@kcore.de>
//
// Snownews is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3
// as published by the Free Software Foundation.
//
// Snownews is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Snownews. If not, see http://www.gnu.org/licenses/.
#pragma once
#include "main.h"
int NetSupportAuth (struct feed* cur_ptr, const char* authdata, const char* url, const char* netbuf);
int checkValidHTTPHeader (const unsigned char* header, unsigned size);
int checkValidHTTPURL (const unsigned char* url);

797
netio.c
View File

@ -1,6 +1,7 @@
// This file is part of Snownews - A lightweight console RSS newsreader
//
// Copyright (c) 2003-2004 Oliver Feiler <kiza@kcore.de>
// Copyright (c) 2021 Mike Sharov <msharov@users.sourceforge.net>
//
// Snownews is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3
@ -15,757 +16,77 @@
// along with Snownews. If not, see http://www.gnu.org/licenses/.
#include "netio.h"
#include "io-internal.h"
#include "net-support.h"
#include "ui-support.h"
#include "zlib_interface.h"
#include <errno.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <syslog.h>
#include <unistd.h>
#include <curl/curl.h>
enum {
MAX_HTTP_REDIRECTS = 10, // Maximum number of redirects we will follow.
NET_TIMEOUT = 20 // Global network timeout in sec
};
enum PollOp {
NET_READ = 1,
NET_WRITE
};
// Waits NET_TIMEOUT seconds for the socket to return data.
//
// Returns
//
// 0 Socket is ready
// -1 Error occurred (netio_error is set)
//
static int NetPoll (struct feed* cur_ptr, const int* my_socket, enum PollOp rw)
static size_t FeedReceiver (void* buffer, size_t msz, size_t nm, void* vpfeed)
{
fd_set fds;
FD_ZERO (&fds);
FD_SET (*my_socket, &fds);
fd_set* prfds = (rw == NET_READ ? &fds : NULL);
fd_set* pwfds = (rw == NET_WRITE ? &fds : NULL);
struct timeval tv = {.tv_sec = NET_TIMEOUT };
if (select (*my_socket + 1, prfds, pwfds, NULL, &tv) == 0) {
cur_ptr->netio_error = NET_ERR_TIMEOUT;
return -1;
struct feed* fp = vpfeed;
size_t size = msz * nm;
char* t = realloc (fp->xmltext, fp->content_length + size + 1);
if (!t) {
fprintf (stderr, "Error: out of memory\n");
exit (EXIT_FAILURE);
}
if (FD_ISSET (*my_socket, &fds))
return 0;
cur_ptr->netio_error = NET_ERR_UNKNOWN;
return -1;
}
// Connect network sockets.
//
// Returns
//
// 0 Connected
// -1 Error occured (netio_error is set)
//
static int NetConnect (int* my_socket, const char* host, struct feed* cur_ptr, bool httpsproto __attribute__((unused)), bool suppressoutput)
{
char* realhost = strdup (host);
unsigned short port;
if (sscanf (host, "%[^:]:%hd", realhost, &port) != 2)
port = 80;
if (!suppressoutput) {
char stmsg[128];
snprintf (stmsg, sizeof (stmsg), _("Downloading \"%s\""), cur_ptr->title ? cur_ptr->title : cur_ptr->feedurl);
UIStatus (stmsg, 0, 0);
}
// 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 _settings.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 (_settings.proxyport == 0) {
// Lookup remote IP.
struct hostent* remotehost = gethostbyname (realhost);
if (!remotehost) {
close (*my_socket);
free (realhost);
cur_ptr->netio_error = NET_ERR_HOST_NOT_FOUND;
return -1;
}
// Set the remote address.
struct sockaddr_in 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.
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.
if (cur_ptr->connectresult != 0) {
// If errno is not EINPROGRESS, the connect went wrong.
if (errno != EINPROGRESS) {
close (*my_socket);
free (realhost);
cur_ptr->netio_error = NET_ERR_CONN_REFUSED;
return -1;
}
if (NetPoll (cur_ptr, my_socket, NET_WRITE) == -1) {
close (*my_socket);
free (realhost);
return -1;
}
// We get errno of connect back via getsockopt SO_ERROR (into connectresult).
socklen_t 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)
return -1;
}
}
} else {
// Lookup proxyserver IP.
struct hostent* remotehost = gethostbyname (_settings.proxyname);
if (!remotehost) {
close (*my_socket);
free (realhost);
cur_ptr->netio_error = NET_ERR_HOST_NOT_FOUND;
return -1;
}
// Set the remote address.
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_port = htons (_settings.proxyport);
memcpy (&address.sin_addr.s_addr, remotehost->h_addr_list[0], remotehost->h_length);
// 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.
if (cur_ptr->connectresult != 0) {
if (errno != EINPROGRESS) {
close (*my_socket);
free (realhost);
cur_ptr->netio_error = NET_ERR_CONN_REFUSED;
return -1;
}
if (NetPoll (cur_ptr, my_socket, NET_WRITE) == -1) {
close (*my_socket);
free (realhost);
return -1;
}
socklen_t 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)
return -1;
}
}
}
free (realhost);
return 0;
}
// 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.
//
static char* NetIO (int* my_socket, char* host, char* url, struct feed* cur_ptr, const char* authdata, bool httpsproto, bool suppressoutput)
{
if (!suppressoutput) {
char stmsg[256];
if (cur_ptr->title == NULL)
snprintf (stmsg, sizeof (stmsg), _("Downloading \"http://%s%s\""), host, url);
else
snprintf (stmsg, sizeof (stmsg), _("Downloading \"%s\""), cur_ptr->title);
UIStatus (stmsg, 0, 0);
}
// 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.
if (cur_ptr->authinfo && cur_ptr->servauth)
if (strstr (cur_ptr->authinfo, " Digest "))
NetSupportAuth (cur_ptr, authdata, url, cur_ptr->servauth);
// Open socket.
FILE* stream = fdopen (*my_socket, "r+");
if (!stream) {
// 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.
cur_ptr->netio_error = NET_ERR_SOCK_ERR;
return NULL;
}
// Again is _settings.proxyport == 0, non proxy mode, otherwise make proxy requests.
if (_settings.proxyport == 0) {
// 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",
url, _settings.useragent, host, cur_ptr->lastmodified, (cur_ptr->authinfo ? cur_ptr->authinfo : ""), (cur_ptr->cookies ? cur_ptr->cookies : ""));
} else {
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\n%s%s\r\n", url, _settings.useragent,
host, (cur_ptr->authinfo ? cur_ptr->authinfo : ""), (cur_ptr->cookies ? cur_ptr->cookies : ""));
}
fflush (stream); // We love Solaris, don't we?
} else {
// 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",
host, url, _settings.useragent, host, cur_ptr->lastmodified, (cur_ptr->authinfo ? cur_ptr->authinfo : ""), (cur_ptr->cookies ? cur_ptr->cookies : ""));
} else {
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\n%s%s\r\n", host, url,
_settings.useragent, host, (cur_ptr->authinfo ? cur_ptr->authinfo : ""), (cur_ptr->cookies ? cur_ptr->cookies : ""));
}
fflush (stream); // We love Solaris, don't we?
}
if (NetPoll (cur_ptr, my_socket, NET_READ) == -1) {
fclose (stream);
return NULL;
}
char servreply[128]; // First line of server reply
if ((fgets (servreply, sizeof (servreply), stream)) == NULL) {
fclose (stream);
return NULL;
}
if (checkValidHTTPHeader ((unsigned char*) servreply, sizeof (servreply)) != 0) {
cur_ptr->netio_error = NET_ERR_HTTP_PROTO_ERR;
fclose (stream);
return NULL;
}
char* tmpstatus = strdup (servreply);
char* savestart = tmpstatus;
char httpstatus[4] = { }; // HTTP status sent by server.
// 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.
return NULL;
}
strncpy (httpstatus, tmpstatus, 3);
free (savestart);
cur_ptr->lasthttpstatus = atoi (httpstatus);
unsigned redirectcount = 0; // Number of HTTP redirects followed.
unsigned tmphttpstatus = cur_ptr->lasthttpstatus;
bool handled = true;
// Check HTTP server response and handle redirects.
do {
switch (tmphttpstatus) {
case 200: // OK
// Received good status from server, clear problem field.
cur_ptr->netio_error = NET_ERR_OK;
cur_ptr->problem = false;
// Avoid looping on 20x status codes.
handled = true;
break;
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
// 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);
return NULL;
}
while (!feof (stream)) {
char netbuf[BUFSIZ]; // Network read buffer.
if ((fgets (netbuf, sizeof (netbuf), stream)) == NULL) {
// Something bad happened. Server sent stupid stuff.
cur_ptr->netio_error = NET_ERR_HTTP_PROTO_ERR;
fclose (stream);
return NULL;
}
if (checkValidHTTPHeader ((unsigned char*) netbuf, sizeof (netbuf)) != 0) {
cur_ptr->netio_error = NET_ERR_HTTP_PROTO_ERR;
fclose (stream);
return NULL;
}
// 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
if (strncasecmp (netbuf, "Location", 8) == 0) {
char* redirecttarget = strdup (netbuf);
char* redirecttargetbase = redirecttarget;
// 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:"
strsep (&redirecttarget, " ");
if (!redirecttarget) {
cur_ptr->problem = true;
cur_ptr->netio_error = NET_ERR_REDIRECT_ERR;
free (redirecttargetbase);
fclose (stream);
return NULL;
}
// Location must start with "http", otherwise switch on quirksmode.
bool quirksmode = false; // IIS operation mode.
if (strncmp (redirecttarget, "http", 4) != 0)
quirksmode = true;
// 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.
char* newlocation;
if (quirksmode) {
unsigned len = 7 + strlen (host) + strlen (redirecttarget) + 3;
newlocation = malloc (len);
memset (newlocation, 0, len);
strcat (newlocation, "http://");
strcat (newlocation, host);
if (redirecttarget[0] != '/')
strcat (newlocation, "/");
strcat (newlocation, redirecttarget);
} else
newlocation = strdup (redirecttarget);
free (redirecttargetbase);
// Change cur_ptr->feedurl on 301.
if (cur_ptr->lasthttpstatus == 301) {
// Check for valid redirection URL
if (checkValidHTTPURL ((unsigned char*) newlocation) != 0) {
cur_ptr->problem = true;
cur_ptr->netio_error = NET_ERR_REDIRECT_ERR;
fclose (stream);
return NULL;
}
if (!suppressoutput) {
UIStatus (_("URL points to permanent redirect, updating with new location..."), 1, 0);
syslog (LOG_NOTICE, _("URL points to permanent redirect, updating with new location..."));
}
free (cur_ptr->feedurl);
if (authdata == NULL)
cur_ptr->feedurl = strdup (newlocation);
else {
// Include authdata in newly constructed URL.
unsigned len = strlen (authdata) + strlen (newlocation) + 2;
cur_ptr->feedurl = malloc (len);
char* newurl = strdup (newlocation);
char* newurlbase = newurl;
strsep (&newurl, "/");
strsep (&newurl, "/");
snprintf (cur_ptr->feedurl, len, "http://%s@%s", authdata, newurl);
free (newurlbase);
}
}
char* newlocationbase = newlocation;
strsep (&newlocation, "/");
strsep (&newlocation, "/");
char* tmphost = newlocation;
// 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 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);
return NULL;
}
char* newhost = strdup (tmphost);
--newlocation;
newlocation[0] = '/';
char* newurl = strdup (newlocation);
free (newlocationbase);
// Close connection.
fclose (stream);
// Reconnect to server.
if (NetConnect (my_socket, newhost, cur_ptr, httpsproto, suppressoutput))
return NULL;
host = newhost;
url = newurl;
goto tryagain;
}
}
break;
case 304:
// 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.
cur_ptr->netio_error = NET_ERR_OK;
cur_ptr->problem = false;
// This should be freed everywhere where we return
// and current feed uses auth.
if (redirectcount > 0 && authdata) {
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)
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.
cur_ptr->netio_error = NET_ERR_HTTP_410;
fclose (stream);
return NULL;
case 400:
cur_ptr->netio_error = NET_ERR_HTTP_NON_200;
fclose (stream);
return NULL;
default:
// unknown error codes have to be treated like the base class
if (handled) {
// first pass, modify error code to base class
handled = false;
tmphttpstatus -= tmphttpstatus % 100;
} else {
// second pass, give up on unknown error base class
cur_ptr->netio_error = NET_ERR_HTTP_NON_200;
syslog (LOG_ERR, "%s", servreply);
fclose (stream);
return NULL;
}
}
} while (!handled);
#ifdef USE_UNSUPPORTED_AND_BROKEN_CODE
bool chunked = false; // Content-Encoding: chunked received?
#endif
bool inflate = false; // Whether feed data needs decompressed with zlib.
bool authfailed = false; // Avoid repeating failed auth requests endlessly.
// Read rest of HTTP header and parse what we need.
while (!feof (stream)) {
if (NetPoll (cur_ptr, my_socket, NET_READ) == -1) {
fclose (stream);
return NULL;
}
char netbuf[BUFSIZ];
if ((fgets (netbuf, sizeof (netbuf), stream)) == NULL)
break;
if (checkValidHTTPHeader ((unsigned char*) netbuf, sizeof (netbuf)) != 0) {
cur_ptr->netio_error = NET_ERR_HTTP_PROTO_ERR;
fclose (stream);
return NULL;
}
if (strncasecmp (netbuf, "Transfer-Encoding", strlen ("Transfer-Encoding")) == 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.
#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)
chunked = true;
#else
cur_ptr->netio_error = NET_ERR_CHUNKED;
cur_ptr->problem = true;
fclose (stream);
return NULL;
#endif
}
// Get last modified date. This is only relevant on HTTP 200.
if ((strncasecmp (netbuf, "Last-Modified", strlen ("Last-Modified")) == 0) && (cur_ptr->lasthttpstatus == 200)) {
char* tmpstring = strdup (netbuf);
char* freeme = tmpstring;
strsep (&tmpstring, " ");
if (tmpstring == NULL)
free (freeme);
else {
free (cur_ptr->lastmodified);
cur_ptr->lastmodified = strdup (tmpstring);
if (cur_ptr->lastmodified[strlen (cur_ptr->lastmodified) - 1] == '\n')
cur_ptr->lastmodified[strlen (cur_ptr->lastmodified) - 1] = '\0';
if (cur_ptr->lastmodified[strlen (cur_ptr->lastmodified) - 1] == '\r')
cur_ptr->lastmodified[strlen (cur_ptr->lastmodified) - 1] = '\0';
free (freeme);
}
}
if (strncasecmp (netbuf, "Content-Encoding", strlen ("Content-Encoding")) == 0) {
if (strstr (netbuf, "gzip"))
inflate = true;
} else if (strncasecmp (netbuf, "Content-Type", strlen ("Content-Type")) == 0) {
char* tmpstring = strdup (netbuf);
char* freeme = tmpstring;
strsep (&tmpstring, " ");
if (tmpstring) {
char* psemicolon = strstr (tmpstring, ";");
if (psemicolon)
*psemicolon = '\0';
free (cur_ptr->content_type);
cur_ptr->content_type = strdup (tmpstring);
if (cur_ptr->content_type[strlen (cur_ptr->content_type) - 1] == '\n')
cur_ptr->content_type[strlen (cur_ptr->content_type) - 1] = '\0';
if (cur_ptr->content_type[strlen (cur_ptr->content_type) - 1] == '\r')
cur_ptr->content_type[strlen (cur_ptr->content_type) - 1] = '\0';
}
free (freeme);
}
// HTTP authentication
//
// RFC 2617
if ((strncasecmp (netbuf, "WWW-Authenticate", strlen ("WWW-Authenticate")) == 0) && (cur_ptr->lasthttpstatus == 401)) {
if (authfailed) {
// 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.
if (netbuf[strlen (netbuf) - 1] == '\n')
netbuf[strlen (netbuf) - 1] = '\0';
if (netbuf[strlen (netbuf) - 1] == '\r')
netbuf[strlen (netbuf) - 1] = '\0';
authfailed = true;
// 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.
switch (NetSupportAuth (cur_ptr, authdata, url, netbuf)) {
case 1:
cur_ptr->netio_error = NET_ERR_AUTH_NO_AUTHINFO;
fclose (stream);
return NULL;
break;
case 2:
cur_ptr->netio_error = NET_ERR_AUTH_GEN_AUTH_ERR;
fclose (stream);
return NULL;
break;
case -1:
cur_ptr->netio_error = NET_ERR_AUTH_UNSUPPORTED;
fclose (stream);
return NULL;
break;
default:
break;
}
// Close current connection and reconnect to server.
fclose (stream);
if ((NetConnect (my_socket, host, cur_ptr, httpsproto, suppressoutput)) != 0) {
return NULL;
}
// 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)) {}
// 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 (redirectcount > 0 && authdata) {
free (host);
free (url);
}
//---------------------
// End of HTTP header
//---------------------
// Init pointer so strncat works.
// Workaround class hack.
char* body = malloc (1);
body[0] = '\0';
unsigned length = 0;
// 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.
char netbuf[BUFSIZ];
size_t retval = fread (netbuf, 1, sizeof (netbuf), stream);
if (retval == 0)
break;
body = realloc (body, length + retval);
memcpy (body + length, netbuf, retval);
length += retval;
if (retval != sizeof (netbuf))
break;
}
body = realloc (body, length + 1);
body[length] = '\0';
cur_ptr->content_length = length;
// Close connection.
fclose (stream);
#ifdef USE_UNSUPPORTED_AND_BROKEN_CODE
if (chunked) {
if (decodechunked (body, &length) == NULL) {
free (body);
cur_ptr->netio_error = NET_ERR_HTTP_PROTO_ERR;
return NULL;
}
}
#endif
// If inflate==true we need to decompress the content..
if (inflate) {
char* inflatedbody;
// gzipinflate
int gzipstatus = jg_gzip_uncompress (body, length, (void **) &inflatedbody, &cur_ptr->content_length);
if (gzipstatus) {
free (body);
syslog (LOG_ERR, _("zlib exited with code: %d"), gzipstatus);
cur_ptr->netio_error = NET_ERR_GZIP_ERR;
return NULL;
}
// Copy uncompressed data back to body.
free (body);
body = inflatedbody;
}
return body;
fp->xmltext = t;
memcpy (&fp->xmltext[fp->content_length], buffer, size);
fp->content_length += size;
fp->xmltext [fp->content_length] = 0;
return size;
}
// 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, bool suppressoutput)
// Various status info put into struct feed* fp.
void DownloadFeed (const char* url, struct feed* fp)
{
if (checkValidHTTPURL ((unsigned char*) url) != 0) {
cur_ptr->problem = true;
cur_ptr->netio_error = NET_ERR_HTTP_PROTO_ERR;
return NULL;
// Default to error
if (fp->xmltext) {
free (fp->xmltext);
fp->xmltext = NULL;
fp->content_length = 0;
}
// strstr will match _any_ substring. Not good, use strncasecmp with length 5!
bool httpsproto = (strncasecmp (url, "https", strlen ("https")) == 0);
fp->problem = true;
strsep (&url, "/");
strsep (&url, "/");
char* tmphost = url;
strsep (&url, "/");
bool url_fixup = false;
if (url == NULL) {
// Assume "/" is input is exhausted.
url = strdup ("/");
url_fixup = true;
}
// If tmphost contains an '@', extract username and pwd.
char* authdata = NULL;
if (strchr (tmphost, '@') != NULL) {
char* tmpstr = tmphost;
strsep (&tmphost, "@");
authdata = strdup (tmpstr);
// libcurl global init must be called only once
// snownews is single threaded, so no fancy locks needed
static bool s_curl_initialized = false;
if (!s_curl_initialized) {
if (0 != curl_global_init (CURL_GLOBAL_DEFAULT)) {
UIStatus ("Error: failed to initialize libcurl", 2, 1);
syslog (LOG_ERR, "failed to initialize libcurl");
return;
}
atexit (curl_global_cleanup);
s_curl_initialized = true;
}
char* host = strdup (tmphost);
CURL* curl = curl_easy_init();
if (!curl)
return;
// netio() might change pointer of host to something else if redirect
// loop is executed. Make a copy so we can correctly free everything.
char* hostbase = host;
// Only run if url was != NULL above.
if (!url_fixup) {
--url;
url[0] = '/';
if (url[strlen (url) - 1] == '\n') {
url[strlen (url) - 1] = '\0';
curl_easy_setopt (curl, CURLOPT_URL, url);
curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, FeedReceiver);
curl_easy_setopt (curl, CURLOPT_WRITEDATA, fp);
char cookiefile [PATH_MAX];
unsigned cfnl = snprintf (cookiefile, sizeof(cookiefile), SNOWNEWS_CONFIG_DIR "cookies", getenv("HOME"));
if (cfnl < sizeof(cookiefile) && access (cookiefile, R_OK) == 0)
curl_easy_setopt (curl, CURLOPT_COOKIEFILE, cookiefile);
CURLcode rc = curl_easy_perform (curl);
curl_easy_cleanup (curl);
if (rc == CURLE_OK)
fp->problem = false;
else if (fp->xmltext) {
free (fp->xmltext);
fp->xmltext = NULL;
fp->content_length = 0;
const char* cerrt = curl_easy_strerror (rc);
if (cerrt) {
UIStatus (cerrt, 2, 1);
syslog (LOG_ERR, "%s", cerrt);
}
}
int my_socket = 0;
if (NetConnect (&my_socket, host, cur_ptr, httpsproto, suppressoutput)) {
free (hostbase);
free (authdata);
if (url_fixup)
free (url);
cur_ptr->problem = true;
return NULL;
}
char* returndata = NetIO (&my_socket, host, url, cur_ptr, authdata, httpsproto, suppressoutput);
if (!returndata && cur_ptr->netio_error != NET_ERR_OK)
cur_ptr->problem = true;
// url will be freed in the calling function.
free (hostbase); // This is *host.
free (authdata);
if (url_fixup)
free (url);
return returndata;
}

View File

@ -1,6 +1,7 @@
// This file is part of Snownews - A lightweight console RSS newsreader
//
// Copyright (c) 2003-2004 Oliver Feiler <kiza@kcore.de>
// Copyright (c) 2021 Mike Sharov <msharov@users.sourceforge.net>
//
// Snownews is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3
@ -17,4 +18,4 @@
#pragma once
#include "main.h"
char* DownloadFeed (char* url, struct feed* cur_ptr, bool suppressoutput);
void DownloadFeed (const char* url, struct feed* cur_ptr);

10
setup.c
View File

@ -17,14 +17,9 @@
#include "setup.h"
#include "main.h"
#include "categories.h"
#include "cookies.h"
#include "io-internal.h"
#include "ui-support.h"
#include <errno.h>
#include <ncurses.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
// Load browser command from ~./snownews/browser.
static void SetupBrowser (const char* filename)
@ -400,11 +395,6 @@ static unsigned SetupFeedList (const char* filename)
for (char *catnext = categories, *catname; (catname = strsep (&catnext, ","));)
FeedCategoryAdd (new_ptr, catname);
// 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.
if (!_feed_list)
_feed_list = new_ptr;

View File

@ -17,7 +17,6 @@
#include "ui-support.h"
#include <ncurses.h>
#include <unistd.h>
// Init the ncurses library.
void InitCurses (void)

View File

@ -1,121 +0,0 @@
// This file is part of Snownews - A lightweight console RSS newsreader
//
// Copyright (c) 2004 Rene Puls <rpuls@gmx.net>
//
// Snownews is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3
// as published by the Free Software Foundation.
//
// Snownews is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Snownews. If not, see http://www.gnu.org/licenses/.
#include "zlib_interface.h"
#include <zlib.h>
struct gzip_header {
unsigned char magic[2];
unsigned char method;
unsigned char flags;
unsigned char mtime[4];
unsigned char xfl;
unsigned char os;
};
struct gzip_footer {
unsigned char crc32[4];
unsigned char size[4];
};
static int jg_zlib_uncompress (void const* in_buf, unsigned in_size, void** out_buf_ptr, unsigned* out_size, bool gzip)
{
// Prepare the stream structure.
z_stream stream = { };
stream.next_in = (void*) in_buf;
stream.avail_in = in_size;
unsigned char tmp_buf[BUFSIZ];
stream.next_out = tmp_buf;
stream.avail_out = sizeof tmp_buf;
if (out_size)
*out_size = 0;
int result = inflateInit2 (&stream, gzip ? MAX_WBITS + 32 : -MAX_WBITS);
if (result)
return JG_ZLIB_ERROR_OLDVERSION;
char* out_buf = NULL;
unsigned out_buf_bytes = 0;
do {
// 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
case Z_ERRNO:
case Z_NEED_DICT:
case Z_MEM_ERROR:
case Z_DATA_ERROR:
case Z_VERSION_ERROR:
inflateEnd (&stream);
free (out_buf);
return JG_ZLIB_ERROR_UNCOMPRESS;
}
if (stream.avail_out < sizeof (tmp_buf)) {
// Add the new uncompressed data to our output buffer.
unsigned 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);
out_buf_bytes += new_bytes;
stream.next_out = tmp_buf;
stream.avail_out = sizeof (tmp_buf);
} else {
// For some reason, inflate() didn't write out a single byte.
inflateEnd (&stream);
free (out_buf);
return JG_ZLIB_ERROR_NODATA;
}
} while (result != Z_STREAM_END);
DONE:
inflateEnd (&stream);
// 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!
if (out_size)
*out_size = out_buf_bytes;
*out_buf_ptr = out_buf;
return 0;
}
// Decompressed gzip,deflate compressed data. This is what the webservers usually send.
int jg_gzip_uncompress (const void* in_buf, unsigned in_size, void** out_buf_ptr, unsigned* out_size)
{
if (out_size)
*out_size = 0;
const struct gzip_header* header = in_buf;
if ((header->magic[0] != 0x1F) || (header->magic[1] != 0x8B))
return JG_ZLIB_ERROR_BAD_MAGIC;
if (header->method != 8)
return JG_ZLIB_ERROR_BAD_METHOD;
if (header->flags != 0 && header->flags != 8)
return JG_ZLIB_ERROR_BAD_FLAGS;
unsigned offset = sizeof (*header);
if (header->flags & 8) // skip the file name
while (offset < in_size)
if (((char*) in_buf)[offset++] == 0)
break;
return jg_zlib_uncompress ((char*) in_buf + offset, in_size - offset - 8, out_buf_ptr, out_size, 0);
}

View File

@ -1,29 +0,0 @@
// This file is part of Snownews - A lightweight console RSS newsreader
//
// Copyright (c) 2004 René Puls <http://purl.org/net/kianga/>
//
// Snownews is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3
// as published by the Free Software Foundation.
//
// Snownews is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Snownews. If not, see http://www.gnu.org/licenses/.
#pragma once
#include "config.h"
enum JG_ZLIB_ERROR {
JG_ZLIB_ERROR_OLDVERSION = -1,
JG_ZLIB_ERROR_UNCOMPRESS = -2,
JG_ZLIB_ERROR_NODATA = -3,
JG_ZLIB_ERROR_BAD_MAGIC = -4,
JG_ZLIB_ERROR_BAD_METHOD = -5,
JG_ZLIB_ERROR_BAD_FLAGS = -6
};
int jg_gzip_uncompress (const void* in_buf, unsigned in_size, void** out_buf_ptr, unsigned* out_size);