From 3e081d85763ebe366c006900f0f9076897edc53f Mon Sep 17 00:00:00 2001 From: Olaf Rempel Date: Mon, 23 Apr 2007 10:23:40 +0200 Subject: [PATCH] initial --- .gitignore | 5 + Makefile | 21 ++++ configfile.c | 217 +++++++++++++++++++++++++++++++++ configfile.h | 15 +++ context.c | 43 +++++++ context.h | 35 ++++++ event.c | 302 ++++++++++++++++++++++++++++++++++++++++++++++ event.h | 42 +++++++ list.h | 268 ++++++++++++++++++++++++++++++++++++++++ logging.c | 102 ++++++++++++++++ logging.h | 19 +++ serial.c | 115 ++++++++++++++++++ serial.h | 6 + statemachine.c | 148 +++++++++++++++++++++++ statemachine.h | 6 + xmodem.c | 156 ++++++++++++++++++++++++ xmodem.h | 9 ++ zyxel-revert.c | 81 +++++++++++++ zyxel-revert.conf | 5 + 19 files changed, 1595 insertions(+) create mode 100644 .gitignore create mode 100644 Makefile create mode 100644 configfile.c create mode 100644 configfile.h create mode 100644 context.c create mode 100644 context.h create mode 100644 event.c create mode 100644 event.h create mode 100644 list.h create mode 100644 logging.c create mode 100644 logging.h create mode 100644 serial.c create mode 100644 serial.h create mode 100644 statemachine.c create mode 100644 statemachine.h create mode 100644 xmodem.c create mode 100644 xmodem.h create mode 100644 zyxel-revert.c create mode 100644 zyxel-revert.conf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f3b2ed6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +*.d +*.o +zyxel-revert +*.log +*.rom diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..ecf25e1 --- /dev/null +++ b/Makefile @@ -0,0 +1,21 @@ +CFLAGS := -O2 -pipe -Wall + +OBJS := configfile.o event.o logging.o +OBJS += context.o serial.o statemachine.o xmodem.o + +all: zyxel-revert + +zyxel-revert: $(OBJS) zyxel-revert.o + $(CC) $(CFLAGS) $^ -o $@ + +%.o: %.c + $(CC) $(CFLAGS) -c $< -o $@ + +%.d: %.c + $(CC) $(CFLAGS) -MM -c $< -o $@ + +clean: + rm -f zyxel-revert *.d *.o *.log + +DEPS := $(wildcard *.c) +-include $(DEPS:.c=.d) diff --git a/configfile.c b/configfile.c new file mode 100644 index 0000000..1314bb3 --- /dev/null +++ b/configfile.c @@ -0,0 +1,217 @@ +/*************************************************************************** + * Copyright (C) 06/2006 by Olaf Rempel * + * razzor@kopf-tisch.de * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "configfile.h" +#include "list.h" +#include "logging.h" + +#define BUFSIZE 1024 + +struct conf_section { + struct list_head list; + struct list_head tupel_list; + const char *name; +}; + +struct conf_tupel { + struct list_head list; + const char *option; + const char *parameter; +}; + +static LIST_HEAD(config_list); + +static struct conf_section * config_add_section(const char *name) +{ + struct conf_section *section; + section = malloc(sizeof(struct conf_section) + strlen(name)); + if (section == NULL) + return NULL; + + INIT_LIST_HEAD(§ion->list); + INIT_LIST_HEAD(§ion->tupel_list); + + section->name = strdup(name); + if (section->name == NULL) { + free(section); + return NULL; + } + + list_add_tail(§ion->list, &config_list); + return section; +} + +static int config_add_tupel(struct conf_section *section, const char *option, const char *parameter) +{ + struct conf_tupel *tupel = malloc(sizeof(struct conf_tupel)); + if (tupel == NULL) + return -1; + + INIT_LIST_HEAD(&tupel->list); + tupel->option = strdup(option); + tupel->parameter = strdup(parameter); + + if (tupel->option == NULL || tupel->parameter == NULL) { + free(tupel); + return -1; + } + + list_add_tail(&tupel->list, §ion->tupel_list); + return 0; +} + +int config_parse(const char *config) +{ + FILE *fz = fopen(config, "r"); + if (fz == NULL) { + log_print(LOG_ERROR, "config_parse(): %s", config); + return -1; + } + + char *line = malloc(BUFSIZE); + if (line == NULL) { + log_print(LOG_ERROR, "config_parse(): out of memory"); + fclose(fz); + return -1; + } + + int linenum = 0; + struct conf_section *section = NULL; + while (fgets(line, BUFSIZE, fz) != NULL) { + linenum++; + + if (line[0] == '#' || line[0] <= ' ') { + continue; + + } else if (line[0] == '[') { + char *tok = strtok(line +1, " ]\n"); + + if (tok == NULL || (section = config_add_section(tok)) == NULL) { + log_print(LOG_WARN, "config_parse(): invalid section in row %d", linenum); + free(line); + fclose(fz); + return -1; + } + continue; + + } else if (section == NULL) { + log_print(LOG_WARN, "config_parse(): missing section in row %d", linenum); + free(line); + fclose(fz); + return -1; + } + + char *tok = strtok(line, " \n"); + if (tok != NULL) { + char *tok2; + while ((tok2 = strtok(NULL, " \n"))) { + if (config_add_tupel(section, tok, tok2) != 0) + log_print(LOG_WARN, "config_parse(): invalid row %d", linenum); + } + } + } + + fclose(fz); + free(line); + return 0; +} + +void config_free(void) +{ + struct conf_section *section, *section_tmp; + struct conf_tupel *tupel, *tupel_tmp; + + list_for_each_entry_safe(section, section_tmp, &config_list, list) { + list_for_each_entry_safe(tupel, tupel_tmp, §ion->tupel_list, list) { + list_del(&tupel->list); + free((char *)tupel->option); + free((char *)tupel->parameter); + free(tupel); + } + list_del(§ion->list); + free(section); + } +} + +static struct conf_section * config_get_section(const char *name) +{ + struct conf_section *section; + + list_for_each_entry(section, &config_list, list) { + if (!strcmp(section->name, name)) + return section; + } + return NULL; +} + +const char * config_get_string(const char *section_str, const char *option, const char *def) +{ + struct conf_section *section = config_get_section(section_str); + if (section != NULL) { + struct conf_tupel *tupel; + list_for_each_entry(tupel, §ion->tupel_list, list) { + if (!strcmp(tupel->option, option)) + return tupel->parameter; + } + } + + if (def != NULL) + log_print(LOG_WARN, "config [%s:%s] not found, using default: '%s'", + section_str, option, def); + return def; +} + +int config_get_int(const char *section, const char *option, int def) +{ + const char *ret = config_get_string(section, option, NULL); + if (ret == NULL) { + log_print(LOG_WARN, "config [%s:%s] not found, using default: '%d'", + section, option, def); + return def; + } + return atoi(ret); +} + +int config_get_strings(const char *section_str, const char *option, + int (*callback)(const char *value, void *privdata), + void *privdata) +{ + struct conf_section *section = config_get_section(section_str); + if (section == NULL) + return -1; + + int cnt = 0; + struct conf_tupel *tupel; + list_for_each_entry(tupel, §ion->tupel_list, list) { + if (!strcmp(tupel->option, option)) + if (callback(tupel->parameter, privdata) == 0) + cnt++; + } + return cnt; +} diff --git a/configfile.h b/configfile.h new file mode 100644 index 0000000..9a2b669 --- /dev/null +++ b/configfile.h @@ -0,0 +1,15 @@ +#ifndef _CONFIG_H_ +#define _CONFIG_H_ + +int config_parse(const char *config); +void config_free(void); + +const char * config_get_string(const char *section_str, const char *option, const char *def); + +int config_get_int(const char *section, const char *option, int def); + +int config_get_strings(const char *section_str, const char *option, + int (*callback)(const char *value, void *privdata), + void *privdata); + +#endif /* _CONFIG_H_ */ diff --git a/context.c b/context.c new file mode 100644 index 0000000..f51c6e1 --- /dev/null +++ b/context.c @@ -0,0 +1,43 @@ +#include +#include + +#include "context.h" +#include "list.h" +#include "logging.h" + +static LIST_HEAD(context_list); + +struct context * create_context(void) +{ + struct context *ctx = malloc(sizeof(struct context)); + if (ctx == NULL) { + log_print(LOG_WARN, "create_context(): out of memory"); + return NULL; + } + + memset(ctx, 0, sizeof(struct context)); + + list_add(&ctx->list, &context_list); + return ctx; +} + +int destroy_context(struct context *ctx) +{ + list_del(&ctx->list); + + if (ctx->dev_close != NULL) + ctx->dev_close(ctx); + + free(ctx); + return 0; +} + +int context_close(void) +{ + struct context *ctx, *tmp; + + list_for_each_entry_safe(ctx, tmp, &context_list, list) + destroy_context(ctx); + + return 0; +} diff --git a/context.h b/context.h new file mode 100644 index 0000000..7975995 --- /dev/null +++ b/context.h @@ -0,0 +1,35 @@ +#ifndef _CONTEXT_H_ +#define _CONTEXT_H_ + +#include "list.h" + +struct context { + struct list_head list; + + /* device local stuff */ + int fd; + int (* dev_close)(struct context *context); + int (* dev_setbaudrate)(struct context *context, int baudrate); + char *devname; + void *dev_privdata; + + /* event stuff */ + struct event_fd *event; + + /* statemachine */ + int state; + + /* line buffer */ + char linebuf[256]; + int linepos; + + /* xmodem */ + int lastpkt; +}; + +struct context * create_context(void); +int destroy_context(struct context *ctx); + +int context_close(void); + +#endif /* _CONTEXT_H_ */ diff --git a/event.c b/event.c new file mode 100644 index 0000000..029c177 --- /dev/null +++ b/event.c @@ -0,0 +1,302 @@ +/*************************************************************************** + * Copyright (C) 10/2006 by Olaf Rempel * + * razzor@kopf-tisch.de * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ +#include +#include +#include + +#include +#include + +#include "list.h" +#include "logging.h" + +#include "event.h" + +static LIST_HEAD(event_fd_list); +static LIST_HEAD(event_timeout_list); + +struct event_fd { + struct list_head list; + unsigned int flags; + int fd; + int (*read_cb)(int fd, void *privdata); + int (*write_cb)(int fd, void *privdata); + void *read_priv; + void *write_priv; +}; + +struct event_timeout { + struct list_head list; + unsigned int flags; + struct timeval intervall; + struct timeval nextrun; + int (*callback)(void *privdata); + void *privdata; +}; + +struct event_fd * event_add_fd( + struct event_fd *entry, + int fd, + int type, + int (*callback)(int fd, void *privdata), + void *privdata) +{ + /* check valid filediskriptor */ + if (fd < 0 || fd > FD_SETSIZE) { + log_print(LOG_ERROR, "event_add_fd(): invalid fd"); + return NULL; + } + + /* check valid type (read/write) */ + if (!(type & FD_TYPES)) { + log_print(LOG_ERROR, "event_add_fd(): invalid type"); + return NULL; + } + + /* create new entry */ + if (entry == NULL) { + entry = malloc(sizeof(struct event_fd)); + if (entry == NULL) { + log_print(LOG_ERROR, "event_add_fd(): out of memory"); + return NULL; + } + + memset(entry, 0, sizeof(struct event_fd)); + entry->flags |= EVENT_NEW; + entry->fd = fd; + + /* put it on the list */ + list_add_tail(&entry->list, &event_fd_list); + } + + if (type & FD_READ) { + entry->flags = (callback != NULL) ? (entry->flags | FD_READ) : (entry->flags & ~FD_READ); + entry->read_cb = callback; + entry->read_priv = privdata; + + } else if (type & FD_WRITE) { + entry->flags = (callback != NULL) ? (entry->flags | FD_WRITE) : (entry->flags & ~FD_WRITE); + entry->write_cb = callback; + entry->write_priv = privdata; + } + + return entry; +} + +int event_get_fd(struct event_fd *entry) +{ + return (entry != NULL) ? entry->fd: -1; +} + +void event_remove_fd(struct event_fd *entry) +{ + /* mark the event as deleted -> remove in select() loop */ + entry->flags |= EVENT_DELETE; +} + +static void add_timeval(struct timeval *ret, struct timeval *a, struct timeval *b) +{ + ret->tv_usec = a->tv_usec + b->tv_usec; + ret->tv_sec = a->tv_sec + b->tv_sec; + + if (ret->tv_usec >= 1000000) { + ret->tv_usec -= 1000000; + ret->tv_sec++; + } +} + +static void sub_timeval(struct timeval *ret, struct timeval *a, struct timeval *b) +{ + ret->tv_usec = a->tv_usec - b->tv_usec; + ret->tv_sec = a->tv_sec - b->tv_sec; + + if (ret->tv_usec < 0) { + ret->tv_usec += 1000000; + ret->tv_sec--; + } +} + +static int cmp_timeval(struct timeval *a, struct timeval *b) +{ + if (a->tv_sec > b->tv_sec) + return -1; + + if (a->tv_sec < b->tv_sec) + return 1; + + if (a->tv_usec > b->tv_usec) + return -1; + + if (a->tv_usec < b->tv_usec) + return 1; + + return 0; +} + +static void schedule_nextrun(struct event_timeout *entry, struct timeval *now) +{ + add_timeval(&entry->nextrun, now, &entry->intervall); + + struct event_timeout *search; + list_for_each_entry(search, &event_timeout_list, list) { + if (search->nextrun.tv_sec > entry->nextrun.tv_sec) { + list_add_tail(&entry->list, &search->list); + return; + + } else if (search->nextrun.tv_sec == entry->nextrun.tv_sec && + search->nextrun.tv_usec > entry->nextrun.tv_usec) { + list_add_tail(&entry->list, &search->list); + return; + } + } + list_add_tail(&entry->list, &event_timeout_list); +} + +struct event_timeout * event_add_timeout( + struct timeval *timeout, + int (*callback)(void *privdata), + void *privdata) +{ + struct event_timeout *entry; + entry = malloc(sizeof(struct event_timeout)); + if (entry == NULL) { + log_print(LOG_ERROR, "event_add_timeout(): out of memory"); + return NULL; + } + + entry->flags = 0; + memcpy(&entry->intervall, timeout, sizeof(entry->intervall)); + entry->callback = callback; + entry->privdata = privdata; + + struct timeval now; + gettimeofday(&now, NULL); + + schedule_nextrun(entry, &now); + return entry; +} + +void event_remove_timeout(struct event_timeout *entry) +{ + /* mark the event as deleted -> remove in select() loop */ + entry->flags |= EVENT_DELETE; +} + +int event_loop(void) +{ + fd_set *fdsets = malloc(sizeof(fd_set) * 2); + if (fdsets == NULL) { + log_print(LOG_ERROR, "event_loop(): out of memory"); + return -1; + } + + while (1) { + struct timeval timeout, *timeout_p = NULL; + if (!list_empty(&event_timeout_list)) { + struct timeval now; + gettimeofday(&now, NULL); + + struct event_timeout *entry, *tmp; + list_for_each_entry_safe(entry, tmp, &event_timeout_list, list) { + if (entry->flags & EVENT_DELETE) { + list_del(&entry->list); + free(entry); + continue; + } + + /* timeout not elapsed, exit search (since list is sorted) */ + if (cmp_timeval(&entry->nextrun, &now) == -1) + break; + + /* remove event from list */ + list_del(&entry->list); + + /* execute callback, when callback returns 0 -> schedule event again */ + if (entry->callback(entry->privdata)) { + free(entry); + + } else { + schedule_nextrun(entry, &now); + } + } + + if (!list_empty(&event_timeout_list)) { + entry = list_entry(event_timeout_list.next, typeof(*entry), list); + + /* calc select() timeout */ + sub_timeval(&timeout, &entry->nextrun, &now); + timeout_p = &timeout; + } + } + + fd_set *readfds = NULL, *writefds = NULL; + struct event_fd *entry, *tmp; + + list_for_each_entry_safe(entry, tmp, &event_fd_list, list) { + entry->flags &= ~EVENT_NEW; + + if (entry->flags & EVENT_DELETE) { + list_del(&entry->list); + free(entry); + + } else if (entry->flags & FD_READ) { + if (readfds == NULL) { + readfds = &fdsets[0]; + FD_ZERO(readfds); + } + FD_SET(entry->fd, readfds); + + } else if (entry->flags & FD_WRITE) { + if (writefds == NULL) { + writefds = &fdsets[1]; + FD_ZERO(writefds); + } + FD_SET(entry->fd, writefds); + } + } + + int i = select(FD_SETSIZE, readfds, writefds, NULL, timeout_p); + if (i <= 0) { + /* On error, -1 is returned, and errno is set + * appropriately; the sets and timeout become + * undefined, so do not rely on their contents + * after an error. + */ + continue; + + } else { + list_for_each_entry(entry, &event_fd_list, list) { + if ((entry->flags & EVENT_NEW) != 0) { + /* entry has just been added, execute it next round */ + continue; + } + + if ((entry->flags & FD_READ) && FD_ISSET(entry->fd, readfds)) + if (entry->read_cb(entry->fd, entry->read_priv) != 0) + entry->flags |= EVENT_DELETE; + + if ((entry->flags & FD_WRITE) && FD_ISSET(entry->fd, writefds)) + if (entry->write_cb(entry->fd, entry->write_priv) != 0) + entry->flags |= EVENT_DELETE; + } + } + } + free(fdsets); +} diff --git a/event.h b/event.h new file mode 100644 index 0000000..05ae63f --- /dev/null +++ b/event.h @@ -0,0 +1,42 @@ +#ifndef _EVENT_H_ +#define _EVENT_H_ + +#include + +#define EVENT_NEW 0x1000 +#define EVENT_DELETE 0x2000 + +#define FD_READ 0x0001 +#define FD_WRITE 0x0002 +#define FD_TYPES (FD_READ | FD_WRITE) + +#define event_add_readfd(entry, fd, callback, privdata) \ + event_add_fd(entry, fd, FD_READ, callback, privdata) + +#define event_add_writefd(entry, fd, callback, privdata) \ + event_add_fd(entry, fd, FD_WRITE, callback, privdata) + +/* inner details are not visible to external users (TODO: size unknown) */ +struct event_fd; +struct event_timeout; + +struct event_fd * event_add_fd( + struct event_fd *entry, + int fd, + int type, + int (*callback)(int fd, void *privdata), + void *privdata); + +int event_get_fd(struct event_fd *entry); +void event_remove_fd(struct event_fd *entry); + +struct event_timeout * event_add_timeout( + struct timeval *timeout, + int (*callback)(void *privdata), + void *privdata); + +void event_remove_timeout(struct event_timeout *entry); + +int event_loop(void); + +#endif /* _EVENT_H_ */ diff --git a/list.h b/list.h new file mode 100644 index 0000000..61f8d93 --- /dev/null +++ b/list.h @@ -0,0 +1,268 @@ +#ifndef _LIST_H_ +#define _LIST_H_ + +/* + * stolen from linux kernel 2.6.11 (http://kernel.org/) + * linux/include/linux/stddef.h (offsetoff) + * linux/include/linux/kernel.h (container_of) + * linux/include/linux/list.h (*list*) + * linux/include/linux/netfilter_ipv4/listhelp.h (LIST_FIND) + * + * modified by Olaf Rempel + */ +#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) + +#define container_of(ptr, type, member) ({ \ + const typeof( ((type *)0)->member ) *__mptr = (ptr); \ + (type *)( (char *)__mptr - offsetof(type,member) );}) + +struct list_head { + struct list_head *next, *prev; +}; + +#define LIST_HEAD_INIT(name) { &(name), &(name) } + +#define LIST_HEAD(name) \ + struct list_head name = LIST_HEAD_INIT(name) + +#define INIT_LIST_HEAD(ptr) do { \ + (ptr)->next = (ptr); (ptr)->prev = (ptr); \ +} while (0) + +/* + * Insert a new entry between two known consecutive entries. + * + * This is only for internal list manipulation where we know + * the prev/next entries already! + */ +static inline void __list_add(struct list_head *new, + struct list_head *prev, + struct list_head *next) +{ + next->prev = new; + new->next = next; + new->prev = prev; + prev->next = new; +} + +/* + * list_add - add a new entry + * @new: new entry to be added + * @head: list head to add it after + * + * Insert a new entry after the specified head. + * This is good for implementing stacks. + */ +static inline void list_add(struct list_head *new, struct list_head *head) +{ + __list_add(new, head, head->next); +} + +/* + * list_add_tail - add a new entry + * @new: new entry to be added + * @head: list head to add it before + * + * Insert a new entry before the specified head. + * This is useful for implementing queues. + */ +static inline void list_add_tail(struct list_head *new, struct list_head *head) +{ + __list_add(new, head->prev, head); +} + +/* + * Delete a list entry by making the prev/next entries + * point to each other. + * + * This is only for internal list manipulation where we know + * the prev/next entries already! + */ +static inline void __list_del(struct list_head * prev, struct list_head * next) +{ + next->prev = prev; + prev->next = next; +} + +/* + * list_del - deletes entry from list. + * @entry: the element to delete from the list. + * Note: list_empty on entry does not return true after this, the entry is + * in an undefined state. + */ +static inline void list_del(struct list_head *entry) +{ + __list_del(entry->prev, entry->next); + entry->next = NULL; + entry->prev = NULL; +} + +/* + * list_del_init - deletes entry from list and reinitialize it. + * entry: the element to delete from the list. + */ +static inline void list_del_init(struct list_head *entry) +{ + __list_del(entry->prev, entry->next); + INIT_LIST_HEAD(entry); +} + +/* + * list_move - delete from one list and add as another's head + * @list: the entry to move + * @head: the head that will precede our entry + */ +static inline void list_move(struct list_head *list, struct list_head *head) +{ + __list_del(list->prev, list->next); + list_add(list, head); +} + +/* + * list_move_tail - delete from one list and add as another's tail + * @list: the entry to move + * @head: the head that will follow our entry + */ +static inline void list_move_tail(struct list_head *list, + struct list_head *head) +{ + __list_del(list->prev, list->next); + list_add_tail(list, head); +} + +/* + * list_empty - tests whether a list is empty + * @head: the list to test. + */ +static inline int list_empty(const struct list_head *head) +{ + return head->next == head; +} + +static inline void __list_splice(struct list_head *list, + struct list_head *head) +{ + struct list_head *first = list->next; + struct list_head *last = list->prev; + struct list_head *at = head->next; + + first->prev = head; + head->next = first; + + last->next = at; + at->prev = last; +} + +/* + * list_splice - join two lists + * @list: the new list to add. + * @head: the place to add it in the first list. + */ +static inline void list_splice(struct list_head *list, struct list_head *head) +{ + if (!list_empty(list)) + __list_splice(list, head); +} + +/* + * list_splice_init - join two lists and reinitialise the emptied list. + * @list: the new list to add. + * @head: the place to add it in the first list. + * + * The list at @list is reinitialised + */ +static inline void list_splice_init(struct list_head *list, + struct list_head *head) +{ + if (!list_empty(list)) { + __list_splice(list, head); + INIT_LIST_HEAD(list); + } +} + +/* + * list_entry - get the struct for this entry + * @ptr: the &struct list_head pointer. + * @type: the type of the struct this is embedded in. + * @member: the name of the list_struct within the struct. + */ +#define list_entry(ptr, type, member) \ + container_of(ptr, type, member) + +/* + * list_for_each - iterate over a list + * @pos: the &struct list_head to use as a loop counter. + * @head: the head for your list. + */ +#define list_for_each(pos, head) \ + for (pos = (head)->next; pos != (head); pos = pos->next) + +/* + * list_for_each_prev - iterate over a list backwards + * @pos: the &struct list_head to use as a loop counter. + * @head: the head for your list. + */ +#define list_for_each_prev(pos, head) \ + for (pos = (head)->prev; pos != (head); pos = pos->prev) + +/* + * list_for_each_safe - iterate over a list safe against removal of list entry + * @pos: the &struct list_head to use as a loop counter. + * @n: another &struct list_head to use as temporary storage + * @head: the head for your list. + */ +#define list_for_each_safe(pos, n, head) \ + for (pos = (head)->next, n = pos->next; pos != (head); \ + pos = n, n = pos->next) + +/* + * list_for_each_entry - iterate over list of given type + * @pos: the type * to use as a loop counter. + * @head: the head for your list. + * @member: the name of the list_struct within the struct. + */ +#define list_for_each_entry(pos, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member); \ + &pos->member != (head); \ + pos = list_entry(pos->member.next, typeof(*pos), member)) + +/* + * list_for_each_entry_reverse - iterate backwards over list of given type. + * @pos: the type * to use as a loop counter. + * @head: the head for your list. + * @member: the name of the list_struct within the struct. + */ +#define list_for_each_entry_reverse(pos, head, member) \ + for (pos = list_entry((head)->prev, typeof(*pos), member); \ + &pos->member != (head); \ + pos = list_entry(pos->member.prev, typeof(*pos), member)) + +/* + * list_for_each_entry_safe - iterate over list of given type safe against removal of list entry + * @pos: the type * to use as a loop counter. + * @n: another type * to use as temporary storage + * @head: the head for your list. + * @member: the name of the list_struct within the struct. + */ +#define list_for_each_entry_safe(pos, n, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member), \ + n = list_entry(pos->member.next, typeof(*pos), member); \ + &pos->member != (head); \ + pos = n, n = list_entry(n->member.next, typeof(*n), member)) + + +/* Return pointer to first true entry, if any, or NULL. A macro + required to allow inlining of cmpfn. */ +#define LIST_FIND(head, cmpfn, type, args...) \ +({ \ + const struct list_head *__i, *__j = NULL; \ + \ + list_for_each(__i, (head)) \ + if (cmpfn((const type)__i , ## args)) { \ + __j = __i; \ + break; \ + } \ + (type)__j; \ +}) + +#endif /* _LIST_H_ */ diff --git a/logging.c b/logging.c new file mode 100644 index 0000000..61dcfcf --- /dev/null +++ b/logging.c @@ -0,0 +1,102 @@ +/*************************************************************************** + * Copyright (C) 06/2006 by Olaf Rempel * + * razzor@kopf-tisch.de * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ +#include +#include +#include +#include +#include +#include + +#include "logging.h" + +#define BUFSIZE 8192 + +static FILE *log_fd = NULL; +static int log_prio = LOG_EVERYTIME; +static char *buffer = NULL; + +int log_print(int prio, const char *fmt, ...) +{ + va_list az; + int len = 0, retval; + + if (prio < log_prio) + return 0; + + if (buffer == NULL) { + buffer = malloc(BUFSIZE); + if (buffer == NULL) { + fprintf(stderr, "log_print(): out of memory\n"); + return -1; + } + } + + if (log_fd != NULL) { + time_t tzgr; + time(&tzgr); + + len += strftime(buffer, BUFSIZE, "%b %d %H:%M:%S :", localtime(&tzgr)); + } + + va_start(az, fmt); + len += vsnprintf(buffer + len, BUFSIZE - len, fmt, az); + va_end(az); + + if (len < 0 || len >= BUFSIZE) { + errno = 0; + return log_print(LOG_ERROR, "log_print: arguments too long"); + } + + if (errno) { + len += snprintf(buffer + len, BUFSIZE - len, ": %s", strerror(errno)); + errno = 0; + } + + retval = fprintf((log_fd ? log_fd : stderr), "%s\n", buffer); + fflush(log_fd); + return retval; +} + +void log_close(void) +{ + if (buffer) + free(buffer); + + if (log_fd) + fclose(log_fd); +} + +int log_init(const char *logfile) +{ + if (log_fd != NULL) + log_close(); + + log_fd = fopen(logfile, "a"); + if (log_fd == NULL) { + fprintf(stderr, "log_init(): can not open logfile"); + return -1; + } + return 0; +} + +void log_setprio(int prio) +{ + log_prio = prio; +} diff --git a/logging.h b/logging.h new file mode 100644 index 0000000..82d028d --- /dev/null +++ b/logging.h @@ -0,0 +1,19 @@ +#ifndef _LOGGING_H_ +#define _LOGGING_H_ + +#define LOG_DEBUG 5 +#define LOG_INFO 4 +#define LOG_NOTICE 3 +#define LOG_WARN 2 +#define LOG_ERROR 1 +#define LOG_CRIT 0 + +#define LOG_EVERYTIME 0 + +int log_init(const char *logfile); +void log_close(void); +void log_setprio(int prio); + +int log_print(int prio, const char *fmt, ... ); + +#endif /* _LOGGING_H_ */ diff --git a/serial.c b/serial.c new file mode 100644 index 0000000..67cf15b --- /dev/null +++ b/serial.c @@ -0,0 +1,115 @@ +#include +#include +#include +#include + +#include +#include + +#include "configfile.h" +#include "context.h" +#include "event.h" +#include "logging.h" +#include "statemachine.h" + +struct serial_device { + struct termios oldtio; + struct termios newtio; +}; + +static int open_serial(struct context *ctx, const char *devname) +{ + struct serial_device *sdev = (struct serial_device *)ctx->dev_privdata; + + ctx->fd = open(devname, O_RDWR); + if (ctx->fd < 0) { + log_print(LOG_ERROR, "open_serial(): open(%s)", devname); + return -1; + } + + ctx->devname = strdup(devname); + + if (tcgetattr(ctx->fd, &sdev->oldtio) != 0) { + log_print(LOG_WARN, "open_serial(): tcgetattr()"); + close(ctx->fd); + return -1; + } + + bzero(&sdev->newtio, sizeof(struct termios)); + sdev->newtio.c_cflag = B9600 | CRTSCTS | CS8 | CLOCAL | CREAD; + + tcflush(ctx->fd, TCIOFLUSH); + + if (tcsetattr(ctx->fd, TCSANOW, &sdev->newtio) != 0) { + log_print(LOG_WARN, "open_serial(): tcsetattr()"); + close(ctx->fd); + return -1; + } + + return 0; +} + +static int setbaudrate(struct context *ctx, int baudrate) +{ + struct serial_device *sdev = (struct serial_device *)ctx->dev_privdata; + + cfsetispeed(&sdev->newtio, baudrate); + cfsetospeed(&sdev->newtio, baudrate); + + /* flush linebuffer */ + ctx->linepos = 0; + + if (tcsetattr(ctx->fd, TCSANOW, &sdev->newtio) != 0) { + log_print(LOG_WARN, "open_serial(): tcsetattr()"); + close(ctx->fd); + return -1; + } + + return 0; +} + +static int close_serial(struct context *ctx) +{ + struct serial_device *sdev = (struct serial_device *)ctx->dev_privdata; + + event_remove_fd(ctx->event); + + tcsetattr(ctx->fd, TCSANOW, &sdev->oldtio); + free(ctx->devname); + close(ctx->fd); + return 0; +} + +static int serial_init_cb(const char *parameter, void *privdata) +{ + struct context *ctx = create_context(); + if (ctx == NULL) + return -1; + + ctx->dev_privdata = malloc(sizeof(struct serial_device)); + if (ctx->dev_privdata == NULL) { + log_print(LOG_WARN, "serial_init_cb(): out of memory"); + destroy_context(ctx); + return -1; + } + + if (open_serial(ctx, parameter) < 0) { + free(ctx->dev_privdata); + destroy_context(ctx); + return -1; + } + + log_print(LOG_EVERYTIME, "listen on %s", ctx->devname); + + ctx->dev_close = close_serial; + ctx->dev_setbaudrate = setbaudrate; + + ctx->event = event_add_readfd(NULL, ctx->fd, statemachine_read, ctx); + return 0; +} + +int serial_init(void) +{ + config_get_strings("ports", "serial", serial_init_cb, NULL); + return 0; +} diff --git a/serial.h b/serial.h new file mode 100644 index 0000000..cf36eb6 --- /dev/null +++ b/serial.h @@ -0,0 +1,6 @@ +#ifndef _SERIAL_H_ +#define _SERIAL_H_ + +int serial_init(void); + +#endif /* _SERIAL_H_ */ diff --git a/statemachine.c b/statemachine.c new file mode 100644 index 0000000..2a18586 --- /dev/null +++ b/statemachine.c @@ -0,0 +1,148 @@ +#include +#include +#include +#include + +#include + +#include "context.h" +#include "logging.h" +#include "xmodem.h" + +/* states */ +enum { + STATE_NONE = 0, + STATE_DEBUG_ASK, /* waiting for "Press any key.." */ + STATE_DEBUG, /* debug mode entered */ + STATE_SWITCH_BAUDRATE, /* switching baudrate */ + STATE_XMODEM, /* xmodem active */ + STATE_XMODEM_COMPLETE, /* xmodem complete */ + STATE_BOOT, /* booting firmware */ +}; + +/* messages */ +char *rx_msg[] = { + "Press any key to enter debug mode within 3 seconds.", + "Enter Debug Mode", + "Now, console speed will be changed to 115200 bps", + "OK", + "Console speed will be changed to 9600 bps", + NULL +}; + +/* message IDs */ +enum { + MSG_DEBUG_ASK = 0, + MSG_DEBUG, + MSG_BAUD_HIGH, + MSG_XMODEM_OK, + MSG_BAUD_LOW, +}; + +static int my_readline(int fd, struct context *ctx, char **retval) +{ + /* TODO: not tested */ + char *newline = memchr(ctx->linebuf, '\r', ctx->linepos); + if (newline != NULL) { + *newline = '\0'; + *retval = strdup(ctx->linebuf); + + ctx->linepos -= (newline - ctx->linebuf); + memmove(ctx->linebuf, newline +1, ctx->linepos); + + return 0; + } + + char buf[32]; + int len = read(fd, buf, sizeof(buf)); + if (len <= 0) + return -1; + + int i; + for (i = 0; i < len; i++) { + /* "understand" backspace */ + if (buf[i] == 0x08 && ctx->linepos > 0) { + ctx->linepos--; + + /* export buffer */ + } else if (buf[i] == '\r' && *retval == NULL) { + ctx->linebuf[ctx->linepos] = '\0'; + + if (ctx->linepos > 0) + *retval = strdup(ctx->linebuf); + + ctx->linepos = 0; + + /* copy */ + } else if (buf[i] >= ' ') { + ctx->linebuf[ctx->linepos++] = buf[i]; + } + } + return 0; +} + +int statemachine_read(int fd, void *privdata) +{ + struct context *ctx = (struct context *)privdata; + + if (ctx->state == STATE_XMODEM) { + if (xmodem_read(fd, privdata) < 0) + ctx->state = STATE_XMODEM_COMPLETE; + + return 0; + } + + char *line = NULL; + if (my_readline(fd, ctx, &line) < 0) + return -1; + + if (line == NULL) + return 0; + + log_print(LOG_DEBUG, "%s: '%s'", ctx->devname, line); + + int msg = 0; + while (rx_msg[msg] != NULL) { + if (strcmp(line, rx_msg[msg]) == 0) + break; + + msg++; + } + + /* wait for "Press any key" */ + if (msg == MSG_DEBUG_ASK) { + ctx->state = STATE_DEBUG_ASK; + write(fd, "\r\n", 2); + + /* debug mode entered */ + } else if (msg == MSG_DEBUG) { + /* if device supports it, switch to high baudrate */ + if (ctx->dev_setbaudrate != NULL) { + ctx->state = STATE_SWITCH_BAUDRATE; + write(fd, "ATBA5\r\n", 7); + + } else { + ctx->state = STATE_XMODEM; + write(fd, "ATLC\r\n", 6); + } + + /* follow device to high baudrate */ + } else if (msg == MSG_BAUD_HIGH) { + ctx->dev_setbaudrate(ctx, B115200); + + ctx->state = STATE_XMODEM; + write(fd, "ATLC\r\n", 6); + + /* transfer was success */ + } else if (msg == MSG_XMODEM_OK && ctx->state == STATE_XMODEM_COMPLETE) { + ctx->state = STATE_BOOT; + write(fd, "ATGR\r\n", 6); + + /* follow device to low baudrate */ + } else if (msg == MSG_BAUD_LOW) { + ctx->dev_setbaudrate(ctx, B9600); + } + + free(line); + return 0; +} diff --git a/statemachine.h b/statemachine.h new file mode 100644 index 0000000..e6f4274 --- /dev/null +++ b/statemachine.h @@ -0,0 +1,6 @@ +#ifndef _STATEMACHINE_H_ +#define _STATEMACHINE_H_ + +int statemachine_read(int fd, void *privdata); + +#endif /* _STATEMACHINE_H_ */ diff --git a/xmodem.c b/xmodem.c new file mode 100644 index 0000000..827f5c9 --- /dev/null +++ b/xmodem.c @@ -0,0 +1,156 @@ +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "configfile.h" +#include "context.h" +#include "logging.h" + +static char *filedata; +static int filesize; + +enum { + XM_SOH = 0x01, + XM_EOT = 0x04, + XM_ACK = 0x06, + XM_NACK = 0x15, + XM_C = 0x43 +}; + +struct xmodem_pkt { + uint8_t header; + uint8_t count; + uint8_t ncount; + uint8_t data[128]; + uint16_t crc; +} __attribute__((packed)); + + +static void calc_crc(struct xmodem_pkt *pkt) +{ + uint16_t crc = 0; + uint8_t *ptr = pkt->data; + + int i, j; + for (i = 0; i < sizeof(pkt->data); i++) { + crc = crc ^ (*ptr++ << 8); + + for (j = 0; j < 8; j++) + crc = (crc & 0x8000) ? (crc << 1 ^ 0x1021) : (crc << 1); + } + + /* byteswap */ + pkt->crc = ((crc & 0xFF00) >> 8) | ((crc & 0xFF) << 8); +} + +int xmodem_read(int fd, void *privdata) +{ + struct context *ctx = (struct context *)privdata; + + struct xmodem_pkt pkt; + + int len = read(fd, &pkt, sizeof(pkt)); + if (len <= 0) { + log_print(LOG_WARN, "xmodem_read(): read()"); + return -1; + } + + int pktnum = 0; + + switch (pkt.header) { + case XM_C: /* first packet */ + log_print(LOG_DEBUG, "%s: XMODEM started", ctx->devname); + pktnum = 0; + break; + + case XM_ACK: /* next packet */ + if (ctx->lastpkt * 128 == filesize) + return -1; + + pktnum = ctx->lastpkt +1; + break; + + case XM_NACK: /* resend last packet */ + pktnum = ctx->lastpkt; + break; + } + + if (pktnum * 128 < filesize) { + pkt.header = XM_SOH; + pkt.count = ((pktnum +1) & 0xFF); + pkt.ncount = 0xFF - pkt.count; + + memcpy(pkt.data, filedata + pktnum * 128, 128); + + calc_crc(&pkt); + write(fd, &pkt, sizeof(pkt)); + + } else { + log_print(LOG_DEBUG, "%s: XMODEM completed", ctx->devname); + pkt.header = XM_EOT; + write(fd, &pkt, 1); + } + + ctx->lastpkt = pktnum; + return 0; +} + +static int load_file_data(const char *filename) +{ + int fd = open(filename, O_RDONLY); + if (fd < 0) { + log_print(LOG_WARN, "load_file_content(): open()"); + return -1; + } + + struct stat filestat; + if (fstat(fd, &filestat) < 0) { + log_print(LOG_WARN, "load_file_content(): fstat()"); + close(fd); + return -1; + } + + filesize = filestat.st_size; + + filedata = malloc(filesize); + if (filedata == NULL) { + log_print(LOG_WARN, "load_file_content(): malloc()"); + close(fd); + return -1; + } + + /* TODO: padding */ + int readsize = read(fd, filedata, filesize); + if (readsize != filesize) { + log_print(LOG_WARN, "load_file_content(): read()"); + free(filedata); + close(fd); + return -1; + } + + close(fd); + return 0; +} + +int xmodem_init(void) +{ + const char *filename = config_get_string("global", "configdata", NULL); + if (filename == NULL) + return -1; + + if (load_file_data(filename) < 0) + return -1; + + return 0; +} + +void xmodem_close(void) +{ + free(filedata); +} diff --git a/xmodem.h b/xmodem.h new file mode 100644 index 0000000..32a9e9f --- /dev/null +++ b/xmodem.h @@ -0,0 +1,9 @@ +#ifndef _XMODEM_H_ +#define _XMODEM_H_ + +int xmodem_init(void); +void xmodem_close(void); + +int xmodem_read(int fd, void *privdata); + +#endif /* _XMODEM_H_ */ diff --git a/zyxel-revert.c b/zyxel-revert.c new file mode 100644 index 0000000..6fd6d47 --- /dev/null +++ b/zyxel-revert.c @@ -0,0 +1,81 @@ +#include +#include +#include +#include + +#include + +#include "configfile.h" +#include "context.h" +#include "event.h" +#include "serial.h" +#include "xmodem.h" + +#define DEFAULT_CONFIG "zyxel-revert.conf" + +static struct option opts[] = { + {"config", 1, 0, 'c'}, + {"debug", 0, 0, 'd'}, + {"help", 0, 0, 'h'}, + {0, 0, 0, 0} +}; + +int main(int argc, char *argv[]) +{ + char *config = DEFAULT_CONFIG; + int code, arg = 0, debug = 0; + + do { + code = getopt_long(argc, argv, "c:dh", opts, &arg); + + switch (code) { + case 'c': /* config */ + config = optarg; + break; + + case 'd': /* debug */ + debug = 1; + break; + + case 'h': /* help */ + printf("Usage: zyxel-revert [options]\n" + "Options: \n" + " --config -c configfile use this configfile\n" + " --debug -d do not fork and log to stderr\n" + " --help -h this help\n" + "\n"); + exit(0); + break; + + case '?': /* error */ + exit(-1); + break; + + default: /* unknown / all options parsed */ + break; + } + } while (code != -1); + + if (config_parse(config)) + exit(1); + + if (serial_init()) + exit(1); + +// if (network_init()) { +// context_close(); +// exit(1); +// } + + if (xmodem_init()) { + context_close(); + exit(1); + } + + event_loop(); + + xmodem_close(); + context_close(); + + return 0; +} diff --git a/zyxel-revert.conf b/zyxel-revert.conf new file mode 100644 index 0000000..7f584ad --- /dev/null +++ b/zyxel-revert.conf @@ -0,0 +1,5 @@ +[global] +configdata 350LI2C1.rom + +[ports] +serial /dev/ttyUSB0