ACL GENPASS: emit 256 bits instead of 128.

--- src/acl.c
+++ src/acl.c
@@ -1819,7 +1819,7 @@
         dictReleaseIterator(di);
         setDeferredArrayLen(c,dl,arraylen);
     } else if (!strcasecmp(sub,"genpass") && c->argc == 2) {
-        char pass[32]; /* 128 bits of actual pseudo random data. */
+        char pass[64]; /* 256 bits of actual pseudo random data. */
         getRandomHexChars(pass,sizeof(pass));
         addReplyBulkCBuffer(c,pass,sizeof(pass));
     } else if (!strcasecmp(sub,"log") && (c->argc == 2 || c->argc ==3)) {


ACL: return error when adding subcommands of fully added commands.

It's almost certainly an error from the user side.

--- src/acl.c
+++ src/acl.c
@@ -485,7 +485,10 @@
  *
  * EINVAL: The specified opcode is not understood.
  * ENOENT: The command name or command category provided with + or - is not
- * known. */
+ *         known.
+ * EBUSY:  The subcommand you want to add is about a command that is currently
+ *         fully added.
+ */
 int ACLSetUser(user *u, const char *op, ssize_t oplen) {
     if (oplen == -1) oplen = strlen(op);
     if (!strcasecmp(op,"on")) {
@@ -568,6 +571,15 @@
                 return C_ERR;
             }

+            /* The command should not be set right now in the command
+             * bitmap, because adding a subcommand of a fully added
+             * command is probably an error on the user side. */
+            if (ACLGetUserCommandBit(u,id) == 1) {
+                zfree(copy);
+                errno = EBUSY;
+                return C_ERR;
+            }
+
             /* Add the subcommand to the list of valid ones. */
             ACLAddAllowedSubcommand(u,id,sub);

@@ -809,6 +821,10 @@
                     errmsg = "unknown command or category name in ACL";
                 else if (errno == EINVAL)
                     errmsg = "syntax error";
+                else if (errno == EBUSY)
+                    errmsg = "adding a subcommand of a command already fully "
+                             "added is not allowed. Remove the command to start. "
+                             "Example: -DEBUG +DEBUG|DIGEST";
                 addReplyErrorFormat(c,
                     "Error in ACL SETUSER modifier '%s': %s",
                     (char*)c->argv[j]->ptr, errmsg);


ACL: split acl.c into clear sections.

ACL: split acl.c into clear sections.


On AOF end of file, truncate the AOF to last valid command.

Recently we introduced the ability to load truncated AOFs, but
unfortuantely the support was broken since the server, after loading the
truncated AOF, continues appending to the file that is corrupted at the
end. The problem is fixed only in the next AOF rewrite.

This commit fixes the issue by truncating the AOF to the last valid
opcode, and aborting if it is not possible to truncate the file
correctly.

--- src/aof.c
+++ src/aof.c
@@ -558,6 +558,7 @@
     struct redis_stat sb;
     int old_aof_state = server.aof_state;
     long loops = 0;
+    off_t valid_up_to = 0; /* Offset of the latest well-formed command loaded. */

     if (fp && redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0) {
         server.aof_current_size = 0;
@@ -647,6 +648,7 @@
         /* Clean up. Command code may have changed argv/argc so we use the
          * argv/argc of the client instead of the local variables. */
         freeFakeClientArgv(fakeClient);
+        if (server.aof_load_truncated) valid_up_to = ftello(fp);
     }

     /* This point can only be reached when EOF is reached without errors.
@@ -671,9 +673,20 @@
 uxeof: /* Unexpected AOF end of file. */
     if (server.aof_load_truncated) {
         redisLog(REDIS_WARNING,"!!! Warning: short read while loading the AOF file !!!");
-        redisLog(REDIS_WARNING,
-            "AOF loaded anyway because aof-load-truncated is enabled");
-        goto loaded_ok;
+        redisLog(REDIS_WARNING,"!!! Truncating the AOF at offset %llu !!!",
+            (unsigned long long) valid_up_to);
+        if (valid_up_to == -1 || truncate(filename,valid_up_to) == -1) {
+            if (valid_up_to == -1) {
+                redisLog(REDIS_WARNING,"Last valid command offset is invalid");
+            } else {
+                redisLog(REDIS_WARNING,"Error truncating the AOF file: %s",
+                    strerror(errno));
+            }
+        } else {
+            redisLog(REDIS_WARNING,
+                "AOF loaded anyway because aof-load-truncated is enabled");
+            goto loaded_ok;
+        }
     }
     redisLog(REDIS_WARNING,"Unexpected end of file reading the append only file. You can: 1) Make a backup of your AOF file, then use ./redis-check-aof --fix <filename>. 2) Alternatively you can set the 'aof-load-truncated' configuration option to yes and restart the server.");
     exit(1);


Fixes  #5: NativeDB.c : Errors when compiling with Visual Studio 2010. Moved declaration of variables before statements. Fixed xCall function header and added return statement to Java_org_sqlite_NativeDB_destroy_1function.

--- src/main/java/org/sqlite/NativeDB.c
+++ src/main/java/org/sqlite/NativeDB.c
@@ -174,7 +174,7 @@
 }

 /* used to call xFunc, xStep and xFinal */
-static xCall(
+static void xCall(
     sqlite3_context *context,
     int args,
     sqlite3_value** value,
@@ -388,7 +388,9 @@
         JNIEnv *env, jobject this, jstring sql)
 {
     sqlite3* db = gethandle(env, this);
-    sqlite3_stmt* stmt;
+    const char *strsql;
+    char* errorMsg;
+    int status;

 	if(!db)
 	{
@@ -396,9 +398,8 @@
 		return 21;
 	}

-    const char *strsql = (*env)->GetStringUTFChars(env, sql, 0);
-    char* errorMsg;
-    int status = sqlite3_exec(db, strsql, 0, 0, &errorMsg);
+    strsql = (*env)->GetStringUTFChars(env, sql, 0);
+    status = sqlite3_exec(db, strsql, 0, 0, &errorMsg);

     (*env)->ReleaseStringUTFChars(env, sql, strsql);

@@ -755,11 +756,15 @@
 JNIEXPORT jint JNICALL Java_org_sqlite_NativeDB_destroy_1function(
         JNIEnv *env, jobject this, jstring name)
 {
+    jint ret = 0;
     const char* strname = (*env)->GetStringUTFChars(env, name, 0);
-    sqlite3_create_function(
+
+    ret = sqlite3_create_function(
         gethandle(env, this), strname, -1, SQLITE_UTF16, 0, 0, 0, 0
     );
     (*env)->ReleaseStringUTFChars(env, name, strname);
+
+    return ret;
 }

 JNIEXPORT void JNICALL Java_org_sqlite_NativeDB_free_1functions(


Stream & AOF: rewrite stream in correct way

--- src/aof.c
+++ src/aof.c
@@ -1121,23 +1121,39 @@
     streamID id;
     int64_t numfields;

-    /* Reconstruct the stream data using XADD commands. */
-    while(streamIteratorGetID(&si,&id,&numfields)) {
-        /* Emit a two elements array for each item. The first is
-         * the ID, the second is an array of field-value pairs. */
-
-        /* Emit the XADD <key> <id> ...fields... command. */
-        if (rioWriteBulkCount(r,'*',3+numfields*2) == 0) return 0;
-        if (rioWriteBulkString(r,"XADD",4) == 0) return 0;
+    if (s->length) {
+        /* Reconstruct the stream data using XADD commands. */
+        while(streamIteratorGetID(&si,&id,&numfields)) {
+            /* Emit a two elements array for each item. The first is
+             * the ID, the second is an array of field-value pairs. */
+
+            /* Emit the XADD <key> <id> ...fields... command. */
+            if (rioWriteBulkCount(r,'*',3+numfields*2) == 0) return 0;
+            if (rioWriteBulkString(r,"XADD",4) == 0) return 0;
+            if (rioWriteBulkObject(r,key) == 0) return 0;
+            if (rioWriteBulkStreamID(r,&id) == 0) return 0;
+            while(numfields--) {
+                unsigned char *field, *value;
+                int64_t field_len, value_len;
+                streamIteratorGetField(&si,&field,&value,&field_len,&value_len);
+                if (rioWriteBulkString(r,(char*)field,field_len) == 0) return 0;
+                if (rioWriteBulkString(r,(char*)value,value_len) == 0) return 0;
+            }
+        }
+        /* Append XSTREAM SETID after XADD, make sure lastid is correct,
+         * in case of XDEL lastid. */
+        if (rioWriteBulkCount(r,'*',4) == 0) return 0;
+        if (rioWriteBulkString(r,"XSTREAM",7) == 0) return 0;
+        if (rioWriteBulkString(r,"SETID",5) == 0) return 0;
         if (rioWriteBulkObject(r,key) == 0) return 0;
-        if (rioWriteBulkStreamID(r,&id) == 0) return 0;
-        while(numfields--) {
-            unsigned char *field, *value;
-            int64_t field_len, value_len;
-            streamIteratorGetField(&si,&field,&value,&field_len,&value_len);
-            if (rioWriteBulkString(r,(char*)field,field_len) == 0) return 0;
-            if (rioWriteBulkString(r,(char*)value,value_len) == 0) return 0;
-        }
+        if (rioWriteBulkStreamID(r,&s->last_id) == 0) return 0;
+    } else {
+        /* Using XSTREAM CREATE if the stream is empty. */
+        if (rioWriteBulkCount(r,'*',4) == 0) return 0;
+        if (rioWriteBulkString(r,"XSTREAM",7) == 0) return 0;
+        if (rioWriteBulkString(r,"CREATE",6) == 0) return 0;
+        if (rioWriteBulkObject(r,key) == 0) return 0;
+        if (rioWriteBulkStreamID(r,&s->last_id) == 0) return 0;
     }

     /* Create all the stream consumer groups. */


Fixed parse error from apple

Fixed parse error from apple

--- src/apn.c
+++ src/apn.c
@@ -685,21 +685,17 @@
     }
 }

-static void __apn_parse_apns_error(const apn_ctx_ref ctx, char *apns_error, char **token, apn_error_ref *error) {
+static void __apn_parse_apns_error(const apn_ctx_ref ctx, char *apns_error, uint32_t *id, apn_error_ref *error) {
     uint8_t cmd = 0;
     uint8_t error_code = 0;
-    uint32_t id = 0;
-
-    if(token){
-        *token = NULL;
-    }
+    uint32_t error_id = 0;

     memcpy(&cmd, apns_error, sizeof(cmd));
-    apns_error++;
+    apns_error += sizeof(cmd);

     if(cmd == 8) {
         memcpy(&error_code, apns_error, sizeof(error_code));
-        apns_error++;
+        apns_error += sizeof(error_code);
         switch(error_code) {
             case APN_APNS_ERR_PROCESSING_ERROR:
                 APN_SET_ERROR(error, APN_ERR_PROCESSING_ERROR | APN_ERR_CLASS_INTERNAL, __apn_errors[APN_ERR_PROCESSING_ERROR]);
@@ -708,11 +704,9 @@
                 APN_SET_ERROR(error, APN_ERR_INVALID_PAYLOAD_SIZE | APN_ERR_CLASS_USER, __apn_errors[APN_ERR_INVALID_PAYLOAD_SIZE]);
                 break;
             case APN_APNS_ERR_INVALID_TOKEN:
-                memcpy(&id, apns_error, sizeof(id));
-                if(token){
-                    if(id <= ctx->__tokens_count) {
-                        *token = ctx->tokens[id];
-                    }
+                memcpy(&error_id, apns_error, sizeof(error_id));
+                if(id){
+                    *id = error_id;
                 }
                 APN_SET_ERROR(error, APN_ERR_TOKEN_INVALID | APN_ERR_CLASS_USER, __apn_errors[APN_ERR_TOKEN_INVALID]);
                 break;
@@ -870,7 +864,8 @@
     char **tokens = NULL;
     uint32_t tokens_count = 0;
     int read = 0;
-
+    uint32_t invalid_id = 0;
+
     if (!ctx) {
         APN_SET_ERROR(error, APN_ERR_CTX_NOT_INITIALIZED | APN_ERR_CLASS_USER, __apn_errors[APN_ERR_CTX_NOT_INITIALIZED]);
         APN_RETURN_ERROR;
@@ -1008,8 +1003,7 @@
     }

     if (has_error) {
-        char *idd = NULL;
-        __apn_parse_apns_error(ctx, apple_error, &idd, error);
+        __apn_parse_apns_error(ctx, apple_error, &invalid_id, error);
         APN_RETURN_ERROR;
     }

@@ -1959,7 +1953,6 @@
         APN_RETURN_ERROR;
     }

-
     property->value.string_value.value = NULL;
     property->value.string_value.length = 0;


do not override default title

do not override default title

--- src/app.c
+++ src/app.c
@@ -42,9 +42,8 @@
   Context* context = (Context*)user_data;

   GtkWindow* window = GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(vte)));
-
   const char* title = vte_terminal_get_window_title(context->vte);
-  if (title && !config_has_str(context->config, "title")) {
+  if (title) {
     gtk_window_set_title(window, title);
   }
 }
@@ -77,7 +76,7 @@

 static bool on_window_focus_in(GtkWindow* window, GdkEvent* event, void* user_data)
 {
-  dd("on_focus in");
+  dd("on focus in");
   UNUSED(event);
   UNUSED(user_data);
   gtk_window_set_urgency_hint(window, false);


cast away 'const' when free()ing user and group

--- src/ast.c
+++ src/ast.c
@@ -14,8 +14,8 @@
 	struct ast_iface *aif;
 	struct ast_domain *ad;

-	free(ast->user);
-	free(ast->group);
+	free((char *)ast->user);
+	free((char *)ast->group);

 	while (!SLIST_EMPTY(&ast->interfaces)) {
 		aif = SLIST_FIRST(&ast->interfaces);


Couple of fixes to ast.h

Couple of fixes to ast.h

1. ast_schema types field shouldn’t be of type enum json_type.  Its values will come from enum json_valuetype.  But b/c it can take OR’d values, it should probably be an int.

2. The field next in struct ast_property_schema should be of type struct ast_property_schema

3. Adds some includes so anything including ast.h will have the types it depends on declared.

--- src/ast.h
+++ src/ast.h
@@ -7,6 +7,9 @@
 #ifndef JVST_AST_H
 #define JVST_AST_H

+#include "jdom.h"
+#include "json.h"
+
 struct fsm;

 typedef json_number ast_number;
@@ -46,7 +49,7 @@
 struct ast_property_schema {
 	struct ast_regexp pattern;
 	struct ast_schema *schema;
-	struct ast_pattern_properties *next;
+	struct ast_property_schema *next;
 };

 /* unordered k/v set */
@@ -179,7 +182,7 @@
 	 */
 	struct ast_value_set *xenum;

-	enum json_type types; /* bitmap; 0 for unset */
+	int types; /* bitmap (see enum json_valuetype); 0 for unset */

 	/*
 	 * "allOf": min = n, max = n


beginning of awk

beginning of awk

error: pathspec 'src/awk.c' did not match any file(s) known to git

--- src/awk.c
+++ src/awk.c
@@ -0,0 +1,65 @@
+#include "lib/common.h"
+
+/*
+#define flag(x)    (flags[opt(x)].count)
+#define lastarg(x) (flags[opt(x)].args[flag(x)-1])
+#define lastnum(x) (flags[opt(x)].nums[flag(x)-1])
+*/
+
+
+static void slurp(char *file, FILE *memstream) {
+  FILE *f = fopen(file, "r");
+  for (int c; (c = fgetc_unlocked(f)) != -1; )
+    fputc_unlocked(c, memstream);
+  fclose(f);
+}
+
+int main(int argc, char *argv[]) {
+  options("f:F:v:");
+
+  struct str script;
+  if (flag('f')) {
+    FILE *memstream = open_memstream(&script.str, &script.len);
+    for (size_t i = 0; i < flag('f'); i++) slurp(flags[opt('f')].args[i], memstream);
+    fclose(memstream);
+  }
+  else
+    script.str = argv[1];
+
+  void *root = 0;
+#define vars(x) tsearch(strdup(x), &root, strcmp)
+#define delete(x) tdelete((x), &root, strcmp)
+  vars("FS") = strdup(flag('F') ? lastarg('F') : " ");
+  for (size_t i = 0; i < flag('v'); i++) {
+    char *ptr = strchr('=', flags[opt('v')].args[i]);
+    if (ptr) {
+      *ptr = 0;
+      vars(flags[opt('v')].args[i]) = strdup(ptr+1);
+    }
+  }
+
+  /*
+
+  size_t linecount = 1;
+  FILE *fileptr = stdin;
+  if (argc == 1)
+    goto inner;
+
+  while (*++argv) {
+    if (argv[0][0] == '-' && argv[0][1] == 0) { file = 0; fileptr = stdin; }
+    else if ((file = open(argv[0], O_RDONLY)) == -1) continue;
+    else fileptr = fdopen(file, "r");
+inner:
+
+    if (argc == 1)
+          goto inner;
+
+      while (*++argv) {
+
+  else if (argc > 1)
+
+
+
+
+  */
+}


do not squash at-max msg in report_dynamorio_problem

SVN-Revision: 939

--- core/utils.c
+++ core/utils.c
@@ -2021,16 +2021,14 @@
     ASSERT_ROOM(reportbuf, curbuf, REPORT_MSG_MAX);
     va_start(ap, fmt);
     len = vsnprintf(curbuf, REPORT_MSG_MAX, fmt, ap);
-    curbuf += (len < 0 ? 0 : len); /* any error, even if at max, and we squash */
-    //NOCHECKIN: seems a bad idea: end up w/ blank msgs
-    //NOCHECKIN: switch to print_to_buffer
+    curbuf += (len == -1 ? REPORT_MSG_MAX : (len < 0 ? 0 : len));
     va_end(ap);

     /* don't use dynamorio_version_string, we don't need copyright notice */
     ASSERT_ROOM(reportbuf, curbuf, REPORT_LEN_VERSION);
     len = snprintf(curbuf, REPORT_LEN_VERSION, "\n%s, %s\n",
                        VERSION_NUMBER_STRING, BUILD_NUMBER_STRING);
-    curbuf += (len < 0 ? 0 : len); /* any error, even if at max, and we squash */
+    curbuf += (len == -1 ? REPORT_LEN_VERSION : (len < 0 ? 0 : len));

     ASSERT_ROOM(reportbuf, curbuf, REPORT_LEN_OPTIONS);
     /* leave room for newline */
@@ -2050,7 +2048,7 @@
          num++, pc = (ptr_uint_t *) *pc) {
         len = snprintf(curbuf, REPORT_LEN_STACK_EACH, PFX" "PFX"\n",
                        pc, *(pc+1));
-        curbuf += (len < 0 ? 0 : len); /* any error, even if at max, and we squash */
+        curbuf += (len == -1 ? REPORT_LEN_STACK_EACH : (len < 0 ? 0 : len));
     }

     /* SYSLOG_INTERNAL and diagnostics expect no trailing newline */


use aof_fsync wrapper instead of fsync(2) in bio.c

--- src/bio.c
+++ src/bio.c
@@ -130,7 +130,7 @@
         if (type == REDIS_BIO_CLOSE_FILE) {
             close((long)job->arg1);
         } else if (type == REDIS_BIO_AOF_FSYNC) {
-            fsync((long)job->arg1);
+            aof_fsync((long)job->arg1);
         } else {
             redisPanic("Wrong job type in bioProcessBackgroundJobs().");
         }


relax truncation of stats from large counts to CURIOSITY

SVN-Revision: 541

--- core/utils.h
+++ core/utils.h
@@ -167,6 +167,10 @@
 /* var = (type) val; should always be preceded by a call to ASSERT_TRUNCATE  */
 /* note that it is also OK to use ASSERT_TRUNCATE(type, type, val) for return values */
 #define ASSERT_TRUNCATE(var, type, val) ASSERT(sizeof(type) == sizeof(var) && \
+                                               CHECK_TRUNCATE_TYPE_##type(val) && \
+                                               "truncating "#var" to "#type)
+#define CURIOSITY_TRUNCATE(var, type, val) \
+    ASSERT_CURIOSITY(sizeof(type) == sizeof(var) && \
                                                CHECK_TRUNCATE_TYPE_##type(val) && \
                                                "truncating "#var" to "#type)
 #define CLIENT_ASSERT_TRUNCATE(var, type, val, msg) \
@@ -1331,7 +1335,7 @@

 #define XSTATS_ADD_DC(dcontext, stat, value) do {                                       \
         stats_int_t stats_add_dc__value = (stats_int_t) (value);                        \
-        ASSERT_TRUNCATE(stats_add_dc__value, stats_int_t, value);                       \
+        CURIOSITY_TRUNCATE(stats_add_dc__value, stats_int_t, value);                    \
         DO_THREAD_STATS(dcontext, THREAD_STAT(dcontext, stat) += stats_add_dc__value);  \
         DO_GLOBAL_STATS(XSTATS_ATOMIC_ADD(GLOBAL_STAT(stat), stats_add_dc__value));     \
     } while (0)
@@ -1341,7 +1345,7 @@
 #define XSTATS_SUB(stat, value) XSTATS_ADD(stat, -(stats_int_t)(value))
 #define XSTATS_ADD_ASSIGN_DC(dcontext, stat, var, value) do {               \
         stats_int_t stats_add_assign_dc__value = (stats_int_t) (value);     \
-        ASSERT_TRUNCATE(stats_add_assign_dc__value, stats_int_t, value);    \
+        CURIOSITY_TRUNCATE(stats_add_assign_dc__value, stats_int_t, value); \
         DO_THREAD_STATS(dcontext,                                           \
             THREAD_STAT(dcontext, stat) += stats_add_assign_dc__value);     \
         /* would normally DO_GLOBAL_STATS(), but need to assign var */      \
@@ -1377,7 +1381,7 @@
                       XSTATS_MAX_DC(stats_max__dcontext, stat_max, stat_cur))
 #define XSTATS_TRACK_MAX(stats_track_max, val) do {                      \
         stats_int_t stats_track_max__value = (stats_int_t) (val);        \
-        ASSERT_TRUNCATE(stats_track_max__value, stats_int_t, val);       \
+        CURIOSITY_TRUNCATE(stats_track_max__value, stats_int_t, val);    \
         XSTATS_WITH_DC(stats_track_max__dcontext,                        \
                       XSTATS_MAX_HELPER(stats_track_max__dcontext,       \
                                        stats_track_max,                  \


remove useless cast.

remove useless cast.

--- src/buf.c
+++ src/buf.c
@@ -78,7 +78,7 @@
 		b = sb;
 	}

-	kore_buf_append(buf, (u_int8_t *)b, l);
+	kore_buf_append(buf, b, l);
 	if (b != sb)
 		free(b);
 }


support CGI interpreter without jail

support CGI interpreter without jail

--- src/cgi.c
+++ src/cgi.c
@@ -335,6 +335,7 @@
     const struct strmap_pair *pair;
     char buffer[512] = "HTTP_";
     size_t i;
+    const char *arg = NULL;

     assert(path != NULL);
     assert(uri != NULL);
@@ -374,7 +375,10 @@
         if (action != NULL)
             path = action;

-        /* XXX interpreter */
+        if (interpreter != NULL) {
+            arg = path;
+            path = interpreter;
+        }
     }

     strmap_rewind(headers);
@@ -393,7 +397,7 @@
         setenv(buffer, pair->value, 1);
     }

-    execl(path, path, NULL);
+    execl(path, path, arg, NULL);
     fprintf(stderr, "exec('%s') failed: %s\n",
             path, strerror(errno));
     _exit(2);


fix account selection.

fix account selection.

--- src/ckc.c
+++ src/ckc.c
@@ -112,8 +112,8 @@
             fprintf(stdout, "  [%d]  %s\n", i, l->s);
         }
         ckc_prompt_number(&t, 1, i-1);
-        for (l = a->head; l != NULL; l = l->next, i++) {
-            if (i == t) {
+        for (l = a->head, i = 0; l != NULL; l = l->next, i++) {
+            if (i == t-1) {
                 account = l->s;
                 break;
             }


contextualize the curl structures into ckl_transport_t

--- src/ckl.c
+++ src/ckl.c
@@ -17,10 +17,17 @@

 #include "ckl_version.h"

+#include <string.h>
 #include <curl/curl.h>
 #include <curl/types.h>
 #include <curl/easy.h>

+
+typedef struct ckl_transport_t {
+  CURL *curl;
+  struct curl_httppost *formpost;
+  struct curl_httppost *lastptr;
+} ckl_transport_t;

 typedef struct ckl_conf_t {
   const char *endpoint;
@@ -35,37 +42,53 @@
 } ckl_msg_t;

-static int msg_to_post_data(CURL *curl, ckl_conf_t *conf, ckl_msg_t* m)
+static int msg_to_post_data(ckl_transport_t *t, ckl_conf_t *conf, ckl_msg_t* m)
 {
-  struct curl_httppost *formpost = NULL;
-  struct curl_httppost *lastptr = NULL;
-
-  curl_formadd(&formpost,
-               &lastptr,
+  curl_formadd(&t->formpost,
+               &t->lastptr,
                CURLFORM_COPYNAME, "username",
                CURLFORM_COPYCONTENTS, m->username,
                CURLFORM_END);

-  curl_formadd(&formpost,
-               &lastptr,
+  curl_formadd(&t->formpost,
+               &t->lastptr,
                CURLFORM_COPYNAME, "hostname",
                CURLFORM_COPYCONTENTS, m->hostname,
                CURLFORM_END);

-  curl_formadd(&formpost,
-               &lastptr,
+  curl_formadd(&t->formpost,
+               &t->lastptr,
                CURLFORM_COPYNAME, "msg",
                CURLFORM_COPYCONTENTS, m->msg,
                CURLFORM_END);

-  curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
+  curl_easy_setopt(t->curl, CURLOPT_HTTPPOST, t->formpost);

   return 0;
 }

+
+static int read_config(ckl_conf_t *conf)
+{
+  /* TODO: parse /etc/ckl.conf, ~/.ckl */
+  conf->endpoint = strdup("http://127.0.0.1/ckl");
+  conf->secret = strdup("super-secret");
+}
+
+static int build_msg(ckl_msg_t *msg)
+{
+
+}
+
 int main(int argc, const char *argv[])
 {
+  ckl_msg_t msg;
+  ckl_conf_t conf;
+  ckl_transport_t *transport;
+
   curl_global_init(CURL_GLOBAL_ALL);

+
+
   return 0;
 }


rewrite con_descend_orientation

rewrite con_descend_orientation

It now uses the container orientation (if it is appropriate, the last focused
one otherwise) to recurse. This works better if the target workspace is in
vertical orientation when you use right/left or if it is in horizontal
orientation but you use up/down.

--- src/con.c
+++ src/con.c
@@ -774,34 +774,6 @@
 }

 /*
- * Recursively walk tree of nodes and check all nodes for condition.  Returns
- * container that matches condition (i.e. leftmost, rightmost, etc.).
- *
- */
-Con *_con_descend_direction(Con *con, Con *next, direction_t direction) {
-    #define DESCEND_DIRECTION(condition) \
-        if (TAILQ_EMPTY(&(con->nodes_head))) \
-            if (!next || condition) \
-                next = con; \
-        NODES_FOREACH(con) \
-            next = _con_descend_direction(child, next, direction); \
-        break;
-
-    switch (direction) {
-        case D_LEFT:
-            DESCEND_DIRECTION(next->rect.x < con->rect.x)
-        case D_RIGHT:
-            DESCEND_DIRECTION(next->rect.x > con->rect.x)
-        case D_UP:
-            DESCEND_DIRECTION(next->rect.y > con->rect.y)
-        case D_DOWN:
-            DESCEND_DIRECTION(next->rect.y < con->rect.y)
-    }
-
-    return next;
-}
-
-/*
  * Returns the leftmost, rightmost, etc. container in sub-tree. For example, if
  * direction is D_LEFT, then we return the rightmost container and if direction
  * is D_RIGHT, we return the leftmost container.  This is because if we are
@@ -809,7 +781,49 @@
  *
  */
 Con *con_descend_direction(Con *con, direction_t direction) {
-    return _con_descend_direction(con, NULL, direction);
+    Con *most;
+    DLOG("con_descend_direction(%p, %d)\n", con, direction);
+    if (direction == D_LEFT || direction == D_RIGHT) {
+        if (con->orientation == HORIZ) {
+            /* If the direction is horizontal, we can use either the first
+             * (D_RIGHT) or the last con (D_LEFT) */
+            if (direction == D_RIGHT)
+                most = TAILQ_FIRST(&(con->nodes_head));
+            else most = TAILQ_LAST(&(con->nodes_head), nodes_head);
+        } else if (con->orientation == VERT) {
+            /* Wrong orientation. We use the last focused con. Within that con,
+             * we recurse to chose the left/right con or at least the last
+             * focused one. */
+            most = TAILQ_FIRST(&(con->focus_head));
+        } else {
+            /* If the con has no orientation set, it’s not a split container
+             * but a container with a client window, so stop recursing */
+            return con;
+        }
+    }
+
+    if (direction == D_UP || direction == D_DOWN) {
+        if (con->orientation == VERT) {
+            /* If the direction is vertical, we can use either the first
+             * (D_DOWN) or the last con (D_UP) */
+            if (direction == D_UP)
+                most = TAILQ_LAST(&(con->nodes_head), nodes_head);
+            else most = TAILQ_FIRST(&(con->nodes_head));
+        } else if (con->orientation == HORIZ) {
+            /* Wrong orientation. We use the last focused con. Within that con,
+             * we recurse to chose the top/bottom con or at least the last
+             * focused one. */
+            most = TAILQ_FIRST(&(con->focus_head));
+        } else {
+            /* If the con has no orientation set, it’s not a split container
+             * but a container with a client window, so stop recursing */
+            return con;
+        }
+    }
+
+    if (!most)
+        return con;
+    return con_descend_direction(most, direction);
 }

 /*


minor edit

minor edit

--- src/cpu.h
+++ src/cpu.h
@@ -1,3 +1 @@
-
 int current_cpus(int pid);
-


add clock TODO

add clock TODO

--- src/cpu.h
+++ src/cpu.h
@@ -16,6 +16,8 @@
 private:
     void next() {
         register_[REG_ZERO] = 0x00;
+
+        // TODO: clock

         // instruction fetch
         instruction_ = mmu_.read_word(pc_);


prototype of state function

prototype of state function

--- src/cpu.h
+++ src/cpu.h
@@ -1,3 +1,9 @@
+#include "process.h"
+
+#define MAXPATH 32
+
 int current_cpus(int pid);

 int nice(int pid);
+
+void state(proc_t *procs);


nieszczęsne dcc.

nieszczęsne dcc.

--- src/dcc.c
+++ src/dcc.c
@@ -361,7 +361,7 @@
 					h->check = GG_CHECK_WRITE;
 					h->timeout = GG_DEFAULT_TIMEOUT;
 					h->uin = tmp;
-					e->type = GG_DCC_EVENT_CLIENT_ACCEPT;
+					e->type = GG_EVENT_DCC_CLIENT_ACCEPT;
 				}

 				return e;


Usunięcie small, bo koliduje z windows.h.

--- src/dcc.c
+++ src/dcc.c
@@ -640,9 +640,9 @@

 		return e;
 	} else {
-		struct gg_dcc_tiny_packet tiny;
-		struct gg_dcc_small_packet small;
-		struct gg_dcc_big_packet big;
+		struct gg_dcc_tiny_packet tiny_pkt;
+		struct gg_dcc_small_packet small_pkt;
+		struct gg_dcc_big_packet big_pkt;
 		int size, tmp, res;
 		unsigned int utmp;
 		socklen_t res_size = sizeof(res);
@@ -694,11 +694,11 @@
 			case GG_STATE_READING_TYPE:
 				gg_debug(GG_DEBUG_MISC, "// gg_dcc_watch_fd() GG_STATE_READING_TYPE\n");

-				gg_dcc_read(h->fd, &small, sizeof(small));
-
-				small.type = gg_fix32(small.type);
-
-				switch (small.type) {
+				gg_dcc_read(h->fd, &small_pkt, sizeof(small_pkt));
+
+				small_pkt.type = gg_fix32(small_pkt.type);
+
+				switch (small_pkt.type) {
 					case 0x0003:	/* XXX */
 						gg_debug(GG_DEBUG_MISC, "// gg_dcc_watch_fd() callback\n");
 						h->type = GG_SESSION_DCC_SEND;
@@ -721,7 +721,7 @@
 						break;

 					default:
-						gg_debug(GG_DEBUG_MISC, "// gg_dcc_watch_fd() unknown dcc type (%.4x) from %ld\n", small.type, h->peer_uin);
+						gg_debug(GG_DEBUG_MISC, "// gg_dcc_watch_fd() unknown dcc type (%.4x) from %ld\n", small_pkt.type, h->peer_uin);
 						e->type = GG_EVENT_DCC_ERROR;
 						e->event.dcc_error = GG_ERROR_DCC_HANDSHAKE;
 				}
@@ -731,11 +731,11 @@
 			case GG_STATE_READING_REQUEST:
 				gg_debug(GG_DEBUG_MISC, "// gg_dcc_watch_fd() GG_STATE_READING_REQUEST\n");

-				gg_dcc_read(h->fd, &small, sizeof(small));
-
-				small.type = gg_fix32(small.type);
-
-				switch (small.type) {
+				gg_dcc_read(h->fd, &small_pkt, sizeof(small_pkt));
+
+				small_pkt.type = gg_fix32(small_pkt.type);
+
+				switch (small_pkt.type) {
 					case 0x0001:	/* XXX */
 						gg_debug(GG_DEBUG_MISC, "// gg_dcc_watch_fd() file transfer request\n");
 						h->state = GG_STATE_READING_FILE_INFO;
@@ -754,7 +754,7 @@
 						break;

 					default:
-						gg_debug(GG_DEBUG_MISC, "// gg_dcc_watch_fd() unknown dcc request (%.4x) from %ld\n", small.type, h->peer_uin);
+						gg_debug(GG_DEBUG_MISC, "// gg_dcc_watch_fd() unknown dcc request (%.4x) from %ld\n", small_pkt.type, h->peer_uin);
 						e->type = GG_EVENT_DCC_ERROR;
 						e->event.dcc_error = GG_ERROR_DCC_HANDSHAKE;
 				}
@@ -782,16 +782,16 @@
 			case GG_STATE_SENDING_FILE_ACK:
 				gg_debug(GG_DEBUG_MISC, "// gg_dcc_watch_fd() GG_STATE_SENDING_FILE_ACK\n");

-				big.type = gg_fix32(0x0006);	/* XXX */
-				big.dunno1 = gg_fix32(h->offset);
-				big.dunno2 = 0;
-
-				gg_dcc_write(h->fd, &big, sizeof(big));
+				big_pkt.type = gg_fix32(0x0006);	/* XXX */
+				big_pkt.dunno1 = gg_fix32(h->offset);
+				big_pkt.dunno2 = 0;
+
+				gg_dcc_write(h->fd, &big_pkt, sizeof(big_pkt));

 				h->state = GG_STATE_READING_FILE_HEADER;
-				h->chunk_size = sizeof(big);
+				h->chunk_size = sizeof(big_pkt);
 				h->chunk_offset = 0;
-				if (!(h->chunk_buf = malloc(sizeof(big)))) {
+				if (!(h->chunk_buf = malloc(sizeof(big_pkt)))) {
 					gg_debug(GG_DEBUG_MISC, "// gg_dcc_watch_fd() out of memory\n");
 					free(e);
 					return NULL;
@@ -804,9 +804,9 @@
 			case GG_STATE_SENDING_VOICE_ACK:
 				gg_debug(GG_DEBUG_MISC, "// gg_dcc_watch_fd() GG_STATE_SENDING_VOICE_ACK\n");

-				tiny.type = 0x01;	/* XXX */
-
-				gg_dcc_write(h->fd, &tiny, sizeof(tiny));
+				tiny_pkt.type = 0x01;	/* XXX */
+
+				gg_dcc_write(h->fd, &tiny_pkt, sizeof(tiny_pkt));

 				h->state = GG_STATE_READING_VOICE_HEADER;
 				h->check = GG_CHECK_READ;
@@ -835,15 +835,15 @@
 				if (h->chunk_offset < h->chunk_size)
 					return e;

-				memcpy(&big, h->chunk_buf, sizeof(big));
+				memcpy(&big_pkt, h->chunk_buf, sizeof(big_pkt));
 				free(h->chunk_buf);
 				h->chunk_buf = NULL;

-				big.type = gg_fix32(big.type);
-				h->chunk_size = gg_fix32(big.dunno1);
+				big_pkt.type = gg_fix32(big_pkt.type);
+				h->chunk_size = gg_fix32(big_pkt.dunno1);
 				h->chunk_offset = 0;

-				if (big.type == 0x0005)	{ /* XXX */
+				if (big_pkt.type == 0x0005)	{ /* XXX */
 					gg_debug(GG_DEBUG_MISC, "// gg_dcc_watch_fd() transfer refused\n");
 					e->type = GG_EVENT_DCC_ERROR;
 					e->event.dcc_error = GG_ERROR_DCC_REFUSED;
@@ -866,9 +866,9 @@
 			case GG_STATE_READING_VOICE_HEADER:
 				gg_debug(GG_DEBUG_MISC, "// gg_dcc_watch_fd() GG_STATE_READING_VOICE_HEADER\n");

-				gg_dcc_read(h->fd, &tiny, sizeof(tiny));
-
-				switch (tiny.type) {
+				gg_dcc_read(h->fd, &tiny_pkt, sizeof(tiny_pkt));
+
+				switch (tiny_pkt.type) {
 					case 0x03:	/* XXX */
 						h->state = GG_STATE_READING_VOICE_SIZE;
 						h->check = GG_CHECK_READ;
@@ -879,7 +879,7 @@
 						gg_debug(GG_DEBUG_MISC, "// gg_dcc_watch_fd() peer breaking connection\n");
 						/* XXX zwracać odpowiedni event */
 					default:
-						gg_debug(GG_DEBUG_MISC, "// gg_dcc_watch_fd() unknown request (%.2x)\n", tiny.type);
+						gg_debug(GG_DEBUG_MISC, "// gg_dcc_watch_fd() unknown request (%.2x)\n", tiny_pkt.type);
 						e->type = GG_EVENT_DCC_ERROR;
 						e->event.dcc_error = GG_ERROR_DCC_HANDSHAKE;
 				}
@@ -889,19 +889,19 @@
 			case GG_STATE_READING_VOICE_SIZE:
 				gg_debug(GG_DEBUG_MISC, "// gg_dcc_watch_fd() GG_STATE_READING_VOICE_SIZE\n");

-				gg_dcc_read(h->fd, &small, sizeof(small));
-
-				small.type = gg_fix32(small.type);
-
-				if (small.type < 16 || small.type > sizeof(buf)) {
-					gg_debug(GG_DEBUG_MISC, "// gg_dcc_watch_fd() invalid voice frame size (%d)\n", small.type);
+				gg_dcc_read(h->fd, &small_pkt, sizeof(small_pkt));
+
+				small_pkt.type = gg_fix32(small_pkt.type);
+
+				if (small_pkt.type < 16 || small_pkt.type > sizeof(buf)) {
+					gg_debug(GG_DEBUG_MISC, "// gg_dcc_watch_fd() invalid voice frame size (%d)\n", small_pkt.type);
 					e->type = GG_EVENT_DCC_ERROR;
 					e->event.dcc_error = GG_ERROR_DCC_NET;

 					return e;
 				}

-				h->chunk_size = small.type;
+				h->chunk_size = small_pkt.type;
 				h->chunk_offset = 0;

 				if (!(h->voice_buf = malloc(h->chunk_size))) {
@@ -998,9 +998,9 @@
 			case GG_STATE_SENDING_VOICE_REQUEST:
 				gg_debug(GG_DEBUG_MISC, "// gg_dcc_watch_fd() GG_STATE_SENDING_VOICE_REQUEST\n");

-				small.type = gg_fix32(0x0003);
-
-				gg_dcc_write(h->fd, &small, sizeof(small));
+				small_pkt.type = gg_fix32(0x0003);
+
+				gg_dcc_write(h->fd, &small_pkt, sizeof(small_pkt));

 				h->state = GG_STATE_READING_VOICE_ACK;
 				h->check = GG_CHECK_READ;
@@ -1011,9 +1011,9 @@
 			case GG_STATE_SENDING_REQUEST:
 				gg_debug(GG_DEBUG_MISC, "// gg_dcc_watch_fd() GG_STATE_SENDING_REQUEST\n");

-				small.type = (h->type == GG_SESSION_DCC_GET) ? gg_fix32(0x0003) : gg_fix32(0x0002);	/* XXX */
-
-				gg_dcc_write(h->fd, &small, sizeof(small));
+				small_pkt.type = (h->type == GG_SESSION_DCC_GET) ? gg_fix32(0x0003) : gg_fix32(0x0002);	/* XXX */
+
+				gg_dcc_write(h->fd, &small_pkt, sizeof(small_pkt));

 				switch (h->type) {
 					case GG_SESSION_DCC_GET:
@@ -1048,9 +1048,9 @@
 					return e;
 				}

-				small.type = gg_fix32(0x0001);	/* XXX */
-
-				gg_dcc_write(h->fd, &small, sizeof(small));
+				small_pkt.type = gg_fix32(0x0001);	/* XXX */
+
+				gg_dcc_write(h->fd, &small_pkt, sizeof(small_pkt));

 				file_info_packet.big.type = gg_fix32(0x0003);	/* XXX */
 				file_info_packet.big.dunno1 = 0;
@@ -1073,10 +1073,10 @@
 			case GG_STATE_READING_FILE_ACK:
 				gg_debug(GG_DEBUG_MISC, "// gg_dcc_watch_fd() GG_STATE_READING_FILE_ACK\n");

-				gg_dcc_read(h->fd, &big, sizeof(big));
+				gg_dcc_read(h->fd, &big_pkt, sizeof(big_pkt));

 				/* XXX sprawdzać wynik */
-				h->offset = gg_fix32(big.dunno1);
+				h->offset = gg_fix32(big_pkt.dunno1);

 				h->state = GG_STATE_SENDING_FILE_HEADER;
 				h->check = GG_CHECK_WRITE;
@@ -1089,10 +1089,10 @@
 			case GG_STATE_READING_VOICE_ACK:
 				gg_debug(GG_DEBUG_MISC, "// gg_dcc_watch_fd() GG_STATE_READING_VOICE_ACK\n");

-				gg_dcc_read(h->fd, &tiny, sizeof(tiny));
-
-				if (tiny.type != 0x01) {
-					gg_debug(GG_DEBUG_MISC, "// invalid reply (%.2x), connection refused\n", tiny.type);
+				gg_dcc_read(h->fd, &tiny_pkt, sizeof(tiny_pkt));
+
+				if (tiny_pkt.type != 0x01) {
+					gg_debug(GG_DEBUG_MISC, "// invalid reply (%.2x), connection refused\n", tiny_pkt.type);
 					e->type = GG_EVENT_DCC_ERROR;
 					e->event.dcc_error = GG_ERROR_DCC_REFUSED;
 					return e;
@@ -1113,14 +1113,14 @@

 				if ((h->chunk_size = h->file_info.size - h->offset) > 4096) {
 					h->chunk_size = 4096;
-					big.type = gg_fix32(0x0003);  /* XXX */
+					big_pkt.type = gg_fix32(0x0003);  /* XXX */
 				} else
-					big.type = gg_fix32(0x0002);  /* XXX */
-
-				big.dunno1 = gg_fix32(h->chunk_size);
-				big.dunno2 = 0;
-
-				gg_dcc_write(h->fd, &big, sizeof(big));
+					big_pkt.type = gg_fix32(0x0002);  /* XXX */
+
+				big_pkt.dunno1 = gg_fix32(h->chunk_size);
+				big_pkt.dunno2 = 0;
+
+				gg_dcc_write(h->fd, &big_pkt, sizeof(big_pkt));

 				h->state = GG_STATE_SENDING_FILE;
 				h->check = GG_CHECK_WRITE;
@@ -1282,8 +1282,8 @@
 					h->state = GG_STATE_READING_FILE_HEADER;
 					h->timeout = GG_DEFAULT_TIMEOUT;
 					h->chunk_offset = 0;
-					h->chunk_size = sizeof(big);
-					if (!(h->chunk_buf = malloc(sizeof(big)))) {
+					h->chunk_size = sizeof(big_pkt);
+					if (!(h->chunk_buf = malloc(sizeof(big_pkt)))) {
 						gg_debug(GG_DEBUG_MISC, "// gg_dcc_watch_fd() out of memory\n");
 						free(e);
 						return NULL;


Implemented retry on SDO timeout in dcf.c.

--- src/dcf.c
+++ src/dcf.c
@@ -43,6 +43,12 @@

 static void send_consise_dcf_loop(CO_Data* d,UNS8 nodeId);

+/* Seek to next NodeID's DCF */
+#define SEEK_NEXT_DCF() \
+   	nodeId=(nodeId+1) % d->dcf_odentry->bSubCount; \
+   	if(nodeId==0) nodeId=1; \
+   	d->dcf_cursor = NULL;
+
 /**
 **
 **
@@ -51,7 +57,7 @@
 */
 static void CheckSDOAndContinue(CO_Data* d, UNS8 nodeId)
 {
-  UNS32 abortCode;
+  UNS32 abortCode = 0;

   if(getWriteResultNetworkDict (d, nodeId, &abortCode) != SDO_FINISHED)
     {
@@ -60,6 +66,13 @@
     }

   closeSDOtransfer(d, nodeId, SDO_CLIENT);
+  /* Timedout ? */
+  if(abortCode == SDOABT_TIMED_OUT){
+    /* Node may not be ready, try another one */
+    /* Warning, this might leed to endless attempts */
+    /* if node does never answer */
+	SEEK_NEXT_DCF()
+  }
   send_consise_dcf_loop(d,nodeId);
 }

@@ -182,11 +195,7 @@
       	}
  	}

-   	/* Check the next element*/
-   	nodeId=(nodeId+1) % d->dcf_odentry->bSubCount;
-   	if(nodeId==0)nodeId=1;
-   	d->dcf_cursor = NULL;
-
+	SEEK_NEXT_DCF()
   }

 }


ignore unconvertable conversion requests

--- src/dic.c
+++ src/dic.c
@@ -27,7 +27,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $Saenaru: saenaru/src/dic.c,v 1.12 2006/10/10 08:12:59 wkpark Exp $
+ * $Saenaru: saenaru/src/dic.c,v 1.13 2006/10/10 11:08:38 wkpark Exp $
  */

 #include <windows.h>
@@ -308,6 +308,7 @@
     {
         if (!*lpb)
         {
+            goto cvk_exit40;
             //
             // make attribute
             //


Add new API for internal buffer management module.

--- pool_memqcache.c
+++ pool_memqcache.c
@@ -85,6 +85,7 @@
 static void pool_discard_buffer(POOL_INTERNAL_BUFFER *buffer);
 static void pool_add_buffer(POOL_INTERNAL_BUFFER *buffer, void *data, size_t len);
 static void *pool_get_buffer(POOL_INTERNAL_BUFFER *buffer, size_t *len);
+static char *pool_get_buffer_pointer(POOL_INTERNAL_BUFFER *buffer);
 static char *pool_get_current_cache_buffer(size_t *len);
 static size_t pool_get_buffer_length(POOL_INTERNAL_BUFFER *buffer);
 static void pool_check_and_discard_cache_buffer(int num_oids, int *oids);
@@ -2607,7 +2608,15 @@
 }

 /*
- * Internal buffer management modules
+ * Internal buffer management modules.
+ * Usage:
+ * 1) Create buffer using pool_create_buffer().
+ * 2) Add data to buffer using pool_add_buffer().
+ * 3) Extract (copied) data from buffer using pool_get_buffer().
+ * 4) Optionaly you can:
+ *		Obtain buffer length by using pool_get_buffer_length().
+ *		Obtain buffer pointer by using pool_get_buffer_pointer().
+ * 5) Discard buffer using pool_discard_buffer().
  */

 /*
@@ -2710,6 +2719,17 @@
 		return 0;

 	return buffer->buflen;
+}
+
+/*
+ * Get internal buffer pointer.
+ */
+static char *pool_get_buffer_pointer(POOL_INTERNAL_BUFFER *buffer)
+{
+	if (buffer == NULL)
+		return NULL;
+
+	return buffer->buf;
 }

 /*


Fix critical bug in DNS resolver.

Fix critical bug in DNS resolver.

--- src/dns.c
+++ src/dns.c
@@ -787,6 +787,7 @@
 		}
 	}
 	else if (r < req->pos) {
+		msg_err ("incomplete send over UDP socket, seems to be internal bug");
 		event_set (&req->io_event, req->sock, EV_WRITE, dns_retransmit_handler, req);
 		event_base_set (req->resolver->ev_base, &req->io_event);
 		event_add (&req->io_event, &req->tv);
@@ -1219,6 +1220,7 @@
 	id = header->qid;
 	if ((req = g_hash_table_lookup (ioc->requests, &id)) == NULL) {
 		/* No such requests found */
+		msg_debug ("DNS request with id %d has not been found for IO channel", (gint)id);
 		return FALSE;
 	}
 	*req_out = req;
@@ -1228,6 +1230,7 @@
 	 */
 	if ((pos = dns_request_reply_cmp (req, in + sizeof (struct dns_header),
 			r - sizeof (struct dns_header))) == NULL) {
+		msg_debug ("DNS request with id %d is for different query, ignoring", (gint)id);
 		return FALSE;
 	}
 	/*
@@ -1324,37 +1327,12 @@
 	req->retransmits ++;
 	serv = req->io->srv;
 	if (req->retransmits >= req->resolver->max_retransmits) {
-		msg_err ("maximum number of retransmits expired for resolving %s of type %s", req->requested_name, dns_strtype (req->type));
+		msg_err ("maximum number of retransmits expired for resolving %s of type %s",
+				req->requested_name, dns_strtype (req->type));
 		dns_check_throttling (req->resolver);
 		req->resolver->errors ++;
 		goto err;
 	}
-	/* Select other server */
-	if (req->resolver->is_master_slave) {
-		serv = (struct rspamd_dns_server *)get_upstream_master_slave (req->resolver->servers,
-					req->resolver->servers_num, sizeof (struct rspamd_dns_server),
-					req->time, DEFAULT_UPSTREAM_ERROR_TIME, DEFAULT_UPSTREAM_DEAD_TIME, DEFAULT_UPSTREAM_MAXERRORS);
-	}
-	else {
-		serv = (struct rspamd_dns_server *)get_upstream_round_robin (req->resolver->servers,
-			req->resolver->servers_num, sizeof (struct rspamd_dns_server),
-			req->time, DEFAULT_UPSTREAM_ERROR_TIME, DEFAULT_UPSTREAM_DEAD_TIME, DEFAULT_UPSTREAM_MAXERRORS);
-	}
-	if (serv == NULL) {
-		goto err;
-	}
-
-	req->io = serv->cur_io_channel;
-	if (req->io == NULL) {
-		msg_err ("cannot find suitable io channel for the server %s", serv->name);
-		goto err;
-	}
-	serv->cur_io_channel = serv->cur_io_channel->next;
-
-	if (req->io->sock == -1) {
-		req->io->sock =  make_universal_socket (serv->name, dns_port, SOCK_DGRAM, TRUE, FALSE, FALSE);
-	}
-	req->sock = req->io->sock;

 	if (req->sock == -1) {
 		goto err;
@@ -1364,10 +1342,13 @@
 	if (r == -1) {
 		goto err;
 	}
+
+	msg_debug ("retransmit DNS request with ID %d", (int)req->id);
 	evtimer_add (&req->timer_event, &req->tv);

 	return;
 err:
+	msg_debug ("error on retransmitting DNS request with ID %d", (int)req->id);
 	rep = memory_pool_alloc0 (req->pool, sizeof (struct rspamd_dns_reply));
 	rep->request = req;
 	rep->code = DNS_RC_SERVFAIL;
@@ -1542,9 +1523,6 @@
 	r = send_dns_request (req);

 	if (r == 1) {
-		/* Add timer event */
-		evtimer_add (&req->timer_event, &req->tv);
-
 		/* Add request to hash table */
 		r = 0;
 		while (g_hash_table_lookup (req->io->requests, &req->id)) {
@@ -1557,6 +1535,8 @@
 				return FALSE;
 			}
 		}
+		/* Add timer event */
+		evtimer_add (&req->timer_event, &req->tv);
 		g_hash_table_insert (req->io->requests, &req->id, req);
 		register_async_event (session, (event_finalizer_t)dns_fin_cb, req,
 				g_quark_from_static_string ("dns resolver"));


change the type of the QR flag, and use dns_p_calcsize with packet.new--the specified prepbufsiz sizes the actual packet data, and not the entire C object

--- src/dns.c
+++ src/dns.c
@@ -757,9 +757,10 @@

 static int pkt_new(lua_State *L) {
 	struct dns_packet *P;
-	size_t size;
-
-	size = luaL_optunsigned(L, 1, DNS_P_QBUFSIZ);
+	size_t prepbufsiz, size;
+
+	prepbufsiz = luaL_optunsigned(L, 1, DNS_P_QBUFSIZ);
+	size = dns_p_calcsize(prepbufsiz);
 	P = memset(lua_newuserdata(L, size), '\0', size);
 	luaL_setmetatable(L, PACKET_CLASS);

@@ -784,7 +785,7 @@

 	lua_newtable(L);

-	lua_pushboolean(L, hdr->qr);
+	lua_pushinteger(L, hdr->qr);
 	lua_setfield(L, -2, "qr");

 	lua_pushinteger(L, hdr->opcode);


añadidas etiquetas para cambiar temperatura

--- src/fan.c
+++ src/fan.c
@@ -5,6 +5,9 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <errno.h>
+
+#define temp_encender 60
+#define temp_apagar 56

 int main(int argc, char *argv[])
 {
@@ -39,7 +42,7 @@
 			dup2(fd[1], STDOUT_FILENO);

 			 // mejor system("source - el script")
-			if(system("sensor | grep -m 1 temp1 | cut -d\" \" -f9 | cut -d\"+\" -f2 | cut -c 1-2") < 0)
+			if(system("sensors | grep -m 1 temp1 | cut -d\" \" -f9 | cut -d\"+\" -f2 | cut -c 1-2") < 0)
 				perror("Se ha producido un error al consultar la temperatura.\n");
 		}
 		else{
@@ -59,10 +62,10 @@
 				exit(EXIT_FAILURE);
 			}

-			if(temp < 58){
+			if(temp < temp_encender){
 				printf("La temperatura es media (%d).\n", temp);

-					if(fan_on && 55 > temp ){
+					if(fan_on && temp_apagar > temp ){
 						fan_on = false;
 						printf("Apagar ventilador\n");
 					}


Geo: fix edge case return values for uniformity.

There were two cases outlined in issue #3512 and PR #3551 where
the Geo API returned unexpected results: empty strings where NULL
replies were expected, or a single null reply where an array was
expected. This violates the Redis principle that Redis replies for
existing keys or elements should be indistinguishable.

This is technically an API breakage so will be merged only into 4.0 and
specified in the changelog in the list of breaking compatibilities, even
if it is not very likely that actual code will be affected, hopefully,
since with the past behavior basically there was to acconut for *both*
the possibilities, and the new behavior is always one of the two, but
in a consistent way.

--- src/geo.c
+++ src/geo.c
@@ -161,7 +161,7 @@
         addReplyError(c,"radius cannot be negative");
         return -1;
     }
-
+
     double to_meters = extractUnitOrReply(c,argv[1]);
     if (to_meters < 0) {
         return -1;
@@ -738,16 +738,15 @@
     int j;

     /* Look up the requested zset */
-    robj *zobj = NULL;
-    if ((zobj = lookupKeyReadOrReply(c, c->argv[1], shared.emptymultibulk))
-        == NULL || checkType(c, zobj, OBJ_ZSET)) return;
+    robj *zobj = lookupKeyRead(c->db, c->argv[1]);
+    if (zobj && checkType(c, zobj, OBJ_ZSET)) return;

     /* Report elements one after the other, using a null bulk reply for
      * missing elements. */
     addReplyMultiBulkLen(c,c->argc-2);
     for (j = 2; j < c->argc; j++) {
         double score;
-        if (zsetScore(zobj, c->argv[j]->ptr, &score) == C_ERR) {
+        if (!zobj || zsetScore(zobj, c->argv[j]->ptr, &score) == C_ERR) {
             addReply(c,shared.nullmultibulk);
         } else {
             /* Decode... */
@@ -782,7 +781,7 @@

     /* Look up the requested zset */
     robj *zobj = NULL;
-    if ((zobj = lookupKeyReadOrReply(c, c->argv[1], shared.emptybulk))
+    if ((zobj = lookupKeyReadOrReply(c, c->argv[1], shared.nullbulk))
         == NULL || checkType(c, zobj, OBJ_ZSET)) return;

     /* Get the scores. We need both otherwise NULL is returned. */


Fix memory leak with recursive square lens

--- src/get.c
+++ src/get.c
@@ -1026,6 +1026,7 @@
                 goto error;
             }

+            FREE(square);
             get_combine(rec_state, lens, 1);
         } else {
             parse_combine(rec_state, lens, 1);


fixed game_of_life_cell() with game_of_life_t.adjacency specified

--- src/gol.c
+++ src/gol.c
@@ -26,6 +26,17 @@
 #include <stdlib.h>
 #include <string.h>
 #include "gol.h"
+
+
+/* This utility function implements a cyclic modular calculation. This means,
+ * for instance, that if a value of -1 is passed for *x*, the result will
+ * be ``v - 1``. */
+static int _casemod(int x, int v) {
+    int r = abs(x % v);
+    if (x < 0) r = v - r;
+    return r;
+}
+

 game_of_life_t* game_of_life_create(
         uint32_t width, uint32_t height, bool adjacency) {
@@ -68,8 +79,8 @@

 cell_t* game_of_life_cell(const game_of_life_t* game, int32_t x, int32_t y) {
     if (game->adjacency) {
-        x = abs(x % game->width);
-        y = abs(y % game->height);
+        x = _casemod(x, game->width);
+        y = _casemod(y, game->height);
     }
     else if (x < 0 || y < 0 || x >= game->width || y >= game->height) {
         return NULL;


Updated a comment

Updated a comment

--- src/gsm.c
+++ src/gsm.c
@@ -1640,7 +1640,7 @@
 	size_t j;
 	unsigned int u;

-	if((p = malloc(len - i + 1)) == NULL) /* XXX 4 times big enough? */
+	if((p = malloc(len - i + 1)) == NULL) /* XXX 2 times big enough? */
 		return NULL;
 	/* FIXME actually parse the header */
 	if(hdr != 0)


Added CMS error 321

Added CMS error 321

--- src/gsm.c
+++ src/gsm.c
@@ -132,6 +132,7 @@
 	{ 304,	N_("Invalid PDU mode parameter")		},
 	{ 310,	N_("SIM not inserted")				},
 	{ 311,	N_("SIM PIN required")				},
+	{ 321,	N_("Invalid memory index")			},
 	{ 0,	NULL						}
 };


gui: bring in to view the selected item

gui: bring in to view the selected item

--- src/gui.c
+++ src/gui.c
@@ -512,6 +512,7 @@
      {
         Elm_Genlist_Item *const item = _gl_nth_get(gl, (unsigned int)index);
         elm_genlist_item_selected_set(item, EINA_TRUE);
+        elm_genlist_item_bring_in(item, ELM_GENLIST_ITEM_SCROLLTO_IN);
      }
 }


Add missing include for 'size_t'

Add missing include for 'size_t'

--- src/gxt.h
+++ src/gxt.h
@@ -8,6 +8,7 @@
 #define _GXTMAKER_GXT_H_

 #include <stdint.h>
+#include <stdlib.h>

 #define GXT_KEY_MAX_LEN 8


The link supervision timeout is host control

--- src/hci.c
+++ src/hci.c
@@ -1438,7 +1438,7 @@
 	struct hci_request rq;

 	memset(&rq, 0, sizeof(rq));
-	rq.ogf    = OGF_STATUS_PARAM;
+	rq.ogf    = OGF_HOST_CTL;
 	rq.ocf    = OCF_READ_LINK_SUPERVISION_TIMEOUT;
 	rq.cparam = &handle;
 	rq.clen   = 2;
@@ -1468,7 +1468,7 @@
 	cp.link_sup_to = timeout;

 	memset(&rq, 0, sizeof(rq));
-	rq.ogf    = OGF_STATUS_PARAM;
+	rq.ogf    = OGF_HOST_CTL;
 	rq.ocf    = OCF_WRITE_LINK_SUPERVISION_TIMEOUT;
 	rq.cparam = &cp;
 	rq.clen   = WRITE_LINK_SUPERVISION_TIMEOUT_CP_SIZE;


Implement imv_add_path

Implement imv_add_path

--- src/imv.c
+++ src/imv.c
@@ -236,8 +236,7 @@

 void imv_add_path(struct imv *imv, const char *path)
 {
-  (void)imv;
-  (void)path;
+  imv_navigator_add(imv->navigator, path, imv->recursive_load);
 }

 bool imv_run(struct imv *imv)


Make mutex() public.

Make mutex() public.

Some methods expect the job mutex to be held by the caller, so the mutex
must be accessible to the outside.

--- src/job.h
+++ src/job.h
@@ -183,6 +183,9 @@
     /** @brief Return the queue policies assigned to this Job. */
     QList<QueuePolicy *> queuePolicies() const;

+    /** The mutex used to protect this job. */
+    QMutex *mutex() const Q_DECL_OVERRIDE;
+
 private:
     Private::Job_Private *d_;

@@ -216,10 +219,6 @@
      * job is the Job that the queue is executing. It is not necessarily equal to this. For example, Jobs that are
      * decorated expose the decorator's address, not the address of the decorated object. */
     void defaultEnd(JobPointer job, Thread *thread) Q_DECL_OVERRIDE;
-
-    /** The mutex used to protect this job. */
-    QMutex *mutex() const Q_DECL_OVERRIDE;
-
 };

 }


cleanup to_addr function

cleanup to_addr function

--- src/kad.c
+++ src/kad.c
@@ -50,7 +50,7 @@
 #endif
 }

-void to_addr( IP *addr, const UCHAR ip[], size_t len, size_t port ) {
+void to_addr( IP *addr, const void *ip, size_t len, unsigned int port ) {
 	memset( addr, '\0', sizeof(IP) );

 	if( len == 4 ) {
@@ -95,7 +95,7 @@
 			if( gconf->af == AF_INET ) {
 				dht_addr4_t *data4 = (dht_addr4_t *) data;
 				for( i = 0; i < (data_len / sizeof(dht_addr4_t)); i++ ) {
-					to_addr( &addr, &data4[i].addr[0], 4, ntohs( data4[i].port ) );
+					to_addr( &addr, &data4[i].addr, 4, ntohs( data4[i].port ) );
 					results_add_addr( results, &addr );
 				}
 			}
@@ -104,7 +104,7 @@
 			if( gconf->af == AF_INET6 ) {
 				dht_addr6_t *data6 = (dht_addr6_t *) data;
 				for( i = 0; i < (data_len / sizeof(dht_addr6_t)); i++ ) {
-					to_addr( &addr, &data6[i].addr[0], 16, ntohs( data6[i].port ) );
+					to_addr( &addr, &data6[i].addr, 16, ntohs( data6[i].port ) );
 					results_add_addr( results, &addr );
 				}
 			}
@@ -131,15 +131,9 @@
 	value = values_find( results->id );
 	if( value ) {
 		if( gconf->af == AF_INET6 ) {
-			IP6 *a = (IP6 *) &addr;
-			a->sin6_family = AF_INET6;
-			a->sin6_port = htons( value->port );
-			memcpy( &a->sin6_addr, &in6addr_loopback, 16 ); // ::1
+			to_addr( &addr, &in6addr_loopback, 16, value->port ); // ::1
 		} else {
-			IP4 *a = (IP4 *) &addr;
-			a->sin_family = AF_INET;
-			a->sin_port = htons( value->port );
-			memcpy( &a->sin_addr, &inaddr_loopback, 4 ); // 127.0.0.1
+			to_addr( &addr, &inaddr_loopback, 4, value->port ); // 127.0.0.1
 		}
 		log_debug( "KAD: Address found in local values: %s\n", str_addr( &addr, addrbuf ) );
 		results_add_addr( results, &addr );
@@ -162,7 +156,7 @@
 		if( id_equal( s->id,  results->id ) ) {
 			for( i = 0; i < s->numpeers; ++i ) {
 				p = &s->peers[i];
-				to_addr( &addr, &p->ip[0], p->len, p->port );
+				to_addr( &addr, &p->ip, p->len, p->port );
 				log_debug( "KAD: Address found in local storage: %s\n", str_addr( &addr, addrbuf ) );
 				results_add_addr( results, &addr );
 			}
@@ -613,7 +607,7 @@
 		dprintf( fd, "Id: %s\n", str_id(s->id, hexbuf ));
 		for( i = 0; i < s->numpeers; ++i ) {
 			p = &s->peers[i];
-			to_addr( &addr, &p->ip[0], p->len, p->port );
+			to_addr( &addr, &p->ip, p->len, p->port );
 			dprintf( fd, "  Peer: %s\n", str_addr( &addr, addrbuf)  );
 		}
 		dprintf( fd, " Found %d peers.\n", i );


Fix a key binding issue with lock modifiers.

--- src/key.c
+++ src/key.c
@@ -72,26 +72,26 @@

 static XModifierKeymap *modmap;

-static LockNode mods[] = {
+static LockNode lockMods[] = {
    { XK_Caps_Lock,   0 },
    { XK_Num_Lock,    0 }
 };

 static KeyNode *bindings;
-static unsigned int modifierMask;
+static unsigned int lockMask;

 static unsigned int GetModifierMask(KeySym key);
 static unsigned int ParseModifierString(const char *str);
 static ModifierNode *GetKeyFromModifier(const char *str);
 static KeySym ParseKeyString(const char *str);
 static int ShouldGrab(KeyType key);
-static void GrabKey(KeyNode *np);
+static void GrabKey(KeyNode *np, Window win);

 /** Initialize key data. */
 void InitializeKeys() {

    bindings = NULL;
-   modifierMask = 0;
+   lockMask = 0;

 }

@@ -99,17 +99,21 @@
 void StartupKeys() {

    KeyNode *np;
+   TrayType *tp;
    int x;

    modmap = JXGetModifierMapping(display);

-   for(x = 0; x < sizeof(mods) / sizeof(mods[0]); x++) {
-      mods[x].mask = GetModifierMask(mods[x].symbol);
-      modifierMask |= mods[x].mask;
-   }
-
+   /* Get the keys that we don't care about (num lock, etc). */
+   for(x = 0; x < sizeof(lockMods) / sizeof(lockMods[0]); x++) {
+      lockMods[x].mask = GetModifierMask(lockMods[x].symbol);
+      lockMask |= lockMods[x].mask;
+   }
+
+   /* Look up and grab the keys. */
    for(np = bindings; np; np = np->next) {

+      /* Determine the modifier mask. */
       np->state = 0;
       if(np->mask & MASK_ALT) {
          np->state |= GetModifierMask(XK_Alt_L);
@@ -130,12 +134,22 @@
          np->state |= GetModifierMask(XK_Super_L);
       }

+      /* Determine the key code. */
       if(!np->code) {
          np->code = JXKeysymToKeycode(display, np->symbol);
       }

+      /* Grab the key if needed. */
       if(ShouldGrab(np->key)) {
-         GrabKey(np);
+
+         /* Grab on the root. */
+         GrabKey(np, rootWindow);
+
+         /* Grab on the trays. */
+         for(tp = GetTrays(); tp; tp = tp->next) {
+            GrabKey(np, tp->window);
+         }
+
       }

    }
@@ -148,14 +162,22 @@
 void ShutdownKeys() {

    ClientNode *np;
+   TrayType *tp;
    int layer;

+   /* Ungrab keys on client windows. */
    for(layer = 0; layer < LAYER_COUNT; layer++) {
       for(np = nodes[layer]; np; np = np->next) {
          JXUngrabKey(display, AnyKey, AnyModifier, np->window);
       }
    }

+   /* Ungrab keys on trays, only really needed if we are restarting. */
+   for(tp = GetTrays(); tp; tp = tp->next) {
+      JXUngrabKey(display, AnyKey, AnyModifier, tp->window);
+   }
+
+   /* Ungrab keys on the root. */
    JXUngrabKey(display, AnyKey, AnyModifier, rootWindow);

 }
@@ -177,9 +199,8 @@
 }

 /** Grab a key. */
-void GrabKey(KeyNode *np) {
-
-   TrayType *tp;
+void GrabKey(KeyNode *np, Window win) {
+
    int x;
    int index, maxIndex;
    unsigned int mask;
@@ -189,23 +210,22 @@
       return;
    }

-   maxIndex = 1 << (sizeof(mods) / sizeof(mods[0]));
+   /* Grab for each lock modifier. */
+   maxIndex = 1 << (sizeof(lockMods) / sizeof(lockMods[0]));
    for(index = 0; index < maxIndex; index++) {

+      /* Compute the modifier mask. */
       mask = 0;
-      for(x = 0; x < sizeof(mods) / sizeof(mods[0]); x++) {
+      for(x = 0; x < sizeof(lockMods) / sizeof(lockMods[0]); x++) {
          if(index & (1 << x)) {
-            mask |= mods[x].mask;
-         }
-      }
-
+            mask |= lockMods[x].mask;
+         }
+      }
       mask |= np->state;
-      JXGrabKey(display, np->code, mask,
-         rootWindow, True, GrabModeAsync, GrabModeAsync);
-      for(tp = GetTrays(); tp; tp = tp->next) {
-         JXGrabKey(display, np->code, mask,
-            tp->window, True, GrabModeAsync, GrabModeAsync);
-      }
+
+      /* Grab the key. */
+      JXGrabKey(display, np->code, mask, win,
+         True, GrabModeAsync, GrabModeAsync);

    }

@@ -218,7 +238,7 @@
    unsigned int state;

    /* Remove modifiers we don't care about from the state. */
-   state = event->state & ~modifierMask;
+   state = event->state & ~lockMask;

    /* Loop looking for a matching key binding. */
    for(np = bindings; np; np = np->next) {
@@ -246,9 +266,13 @@
 void RunKeyCommand(const XKeyEvent *event) {

    KeyNode *np;
+   unsigned int state;
+
+   /* Remove the lock key modifiers. */
+   state = event->state & ~lockMask;

    for(np = bindings; np; np = np->next) {
-      if(np->state == event->state && np->code == event->keycode) {
+      if(np->state == state && np->code == event->keycode) {
          RunCommand(np->command);
          return;
       }
@@ -261,9 +285,13 @@

    KeyNode *np;
    int button;
+   unsigned int state;
+
+   /* Remove the lock key modifiers. */
+   state = event->state & ~lockMask;

    for(np = bindings; np; np = np->next) {
-      if(np->state == event->state && np->code == event->keycode) {
+      if(np->state == state && np->code == event->keycode) {
          button = atoi(np->command);
          if(button >= 0 && button <= 9) {
             ShowRootMenu(button, 0, 0);
@@ -304,9 +332,8 @@
    KeyNode *kp;

    for(kp = bindings; kp; kp = kp->next) {
-      if(ShouldGrab(kp->key) && kp->code) {
-         JXGrabKey(display, kp->code, kp->state,
-            np->window, True, GrabModeAsync, GrabModeAsync);
+      if(ShouldGrab(kp->key)) {
+         GrabKey(kp, np->window);
       }
    }


*** empty log message ***

*** empty log message ***

--- src/l2a.c
+++ src/l2a.c
@@ -159,7 +159,6 @@
 {
    if (id < 0)
    {
-      //fprintf(stderr, "id = %d\n", id);
       return(archsregs[-IREGBEG-id]);
    }
    else if (id)
@@ -1237,14 +1236,14 @@
    #ifdef X86_64
       case CVTSI: /* convert 32bit to 64 bit int*/
 /*
- *    Majedul: we will use movslq for this
- */
-   #if 0
+ *    Majedul: we are using  movslq for this
+ */
+      #if 0
          k = -iName2Reg("@rax");
          assert(op1 == k && op2 == k);
          ap->next = PrintAssln("\tcltq\n");
 /*         ap->next = PrintAssln("\tcdqe\n"); */
-   #else
+      #else
          if (op1 < 0)
             ap->next = PrintAssln("\tmovslq\t%s, %s\n",
                                   GetSregOrDeref(op2),
@@ -1254,7 +1253,7 @@
                                    archsregs[-IREGBEG-op2],
                                    GetIregOrDeref(op1));

-   #endif
+      #endif
          break;
       case CVTIS:
          ap->next = PrintAssln("movl\t%s,%s\n", archiregs[-IREGBEG-op2],
@@ -2713,7 +2712,7 @@

       case COMMENT:
          #ifdef X86
-            //continue; /* skip comments temporary for testing with ATLAS*/
+            /*continue;*/ /* skip comments temporary for testing with ATLAS*/
             ap->next = PrintAssln("#%s\n", op1 ? STname[op1-1] : "");
          #elif defined(SPARC)
             ap->next = PrintAssln("!%s\n", op1 ? STname[op1-1] : "");
@@ -2755,7 +2754,8 @@
  *    FIXME: vpinsrd works on 32 bit ireg like: eax instead of rax...
  *    Only 8 of the 16 IREG has 32 bit version. If we don't make SREG visible,
  *    it will eventually cause problem.
- *    sirk3amax => -rc -V -Ps b A 0 4 -P all 0 128 -U 2
+ *    sirk3amax => -rc -V -Ps b A 0 4 -P all 0 128 -U 2
+ *    NOTE: added an assertion here
  */
       case VGR2VR32:
          op1 = -op1;
@@ -4781,13 +4781,9 @@
  *          FIXME
  */
          cp = imap2cmap(SToff[op3-1].i); /* return hex char */
-#if 0
-         fprintf(stderr, "%x%x%x%x%x%x%x%x\n",cp[7],cp[6],cp[5],cp[4],cp[3],
-                 cp[2],cp[1],cp[0]);
-         //fflush(stderr);
-#endif
          #if defined(AVX) && !defined(AVX2)
-            fko_error(__LINE__, "vishuf is not implemented in AVX,AVX2 needed!\n");
+            fko_error(__LINE__,
+                      "vishuf is not implemented in AVX. AVX2 needed!\n");

          #elif defined(AVX2)
             if (!SToff[op3-1].i)
@@ -4981,7 +4977,7 @@
 /*
  *       NOTE: we are implementing this using vpblendvb (AVX2) but use imm!!
  *       let's use vpblendvb... should work with the mask
- *       this inst selecls byte values from mask specified in the high bit of
+ *       this inst selects byte values from mask specified in the high bit of
  *       each byte. Here, we use mask with all 1's or 0's in each 32bit/64bit.
  *       so, it should work.
  *       NOTE: we support no memory operation now.


Better memory usage; use CF_OEMTEXT instead of CF_TEXT in the narrow versions of the clipboard functions, to match the console.

--- win32/pdcclip.c
+++ win32/pdcclip.c
@@ -13,7 +13,7 @@

 #include "pdcwin.h"

-RCSID("$Id: pdcclip.c,v 1.24 2007/04/28 01:08:40 wmcbrine Exp $");
+RCSID("$Id: pdcclip.c,v 1.25 2007/04/29 02:19:47 wmcbrine Exp $");

 /*man-start**************************************************************

@@ -54,6 +54,12 @@

 **man-end****************************************************************/

+#ifdef PDC_WIDE
+# define PDC_TEXT CF_UNICODETEXT
+#else
+# define PDC_TEXT CF_OEMTEXT
+#endif
+
 int PDC_getclipboard(char **contents, long *length)
 {
 	HANDLE handle;
@@ -64,11 +70,7 @@
 	if (!OpenClipboard(NULL))
 		return PDC_CLIP_ACCESS_ERROR;

-#ifdef PDC_WIDE
-	if ((handle = GetClipboardData(CF_UNICODETEXT)) == NULL)
-#else
-	if ((handle = GetClipboardData(CF_TEXT)) == NULL)
-#endif
+	if ((handle = GetClipboardData(PDC_TEXT)) == NULL)
 	{
 		CloseClipboard();
 		return PDC_CLIP_EMPTY;
@@ -76,11 +78,11 @@

 #ifdef PDC_WIDE
 	len = wcslen((wchar_t *)handle);
+	*contents = (char *)GlobalAlloc(GMEM_FIXED, len * 3 + 1);
 #else
 	len = strlen((char *)handle);
+	*contents = (char *)GlobalAlloc(GMEM_FIXED, len + 1);
 #endif
-	*contents = (char *)GlobalAlloc(GMEM_FIXED,
-		(len + 1) * sizeof(TCHAR));

 	if (!*contents)
 	{
@@ -89,7 +91,7 @@
 	}

 #ifdef PDC_WIDE
-	PDC_wcstombs((char *)*contents, (wchar_t *)handle, len * 2);
+	PDC_wcstombs((char *)*contents, (wchar_t *)handle, len * 3);
 	*length = strlen((char *)*contents);
 #else
 	strcpy((char *)*contents, (char *)handle);
@@ -126,11 +128,7 @@
 	GlobalUnlock(ptr1);
 	EmptyClipboard();

-#ifdef PDC_WIDE
-	if (!SetClipboardData(CF_UNICODETEXT, ptr1))
-#else
-	if (!SetClipboardData(CF_TEXT, ptr1))
-#endif
+	if (!SetClipboardData(PDC_TEXT, ptr1))
 	{
 		GlobalFree(ptr1);
 		return PDC_CLIP_ACCESS_ERROR;


Replacing the switch inside decode_inter by a function table, to prepare for higher register pressure (Yay...)

--- edge264_inter_ssse3.c
+++ edge264_inter_ssse3.c
@@ -1,9 +1,9 @@
+// TODO: Replace the luma switch by a function table
 // TODO: Add pmaddubsw weighting in the functions
 // TODO: There are 3 cases for initializing weights:
 //       - put values without weighting (if single non-weighted or first of pair)
 //       - put values with single weighting (if single weighted)
 //       - put values with double weighting (if second of pair)
-// TODO: Replace the luma switch by a function table
 // TODO: Invert X&Y in QPEL to match ffmpeg convention
 // TODO: Does restrict allow compilers to reorder reads/writes?
 // TODO: Add support for 16bit
@@ -1160,6 +1160,21 @@
 __attribute__((noinline)) void FUNC(decode_inter, int i, int w, int h, int x, int y) {
 	static int8_t shift_Y_8bit[46] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15};
 	static int8_t shift_C_8bit[22] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7};
+	static void FUNC((*luma_fcts[48]), int, size_t, uint8_t*, size_t, uint8_t*) = {
+		inter4xH_qpel00_8bit, inter4xH_qpel01_8bit, inter4xH_qpel02_8bit, inter4xH_qpel03_8bit,
+		inter4xH_qpel10_8bit, inter4xH_qpel11_8bit, inter4xH_qpel12_8bit, inter4xH_qpel13_8bit,
+		inter4xH_qpel20_8bit, inter4xH_qpel21_8bit, inter4xH_qpel22_8bit, inter4xH_qpel23_8bit,
+		inter4xH_qpel30_8bit, inter4xH_qpel31_8bit, inter4xH_qpel32_8bit, inter4xH_qpel33_8bit,
+		inter8xH_qpel00_8bit, inter8xH_qpel01_8bit, inter8xH_qpel02_8bit, inter8xH_qpel03_8bit,
+		inter8xH_qpel10_8bit, inter8xH_qpel11_8bit, inter8xH_qpel12_8bit, inter8xH_qpel13_8bit,
+		inter8xH_qpel20_8bit, inter8xH_qpel21_8bit, inter8xH_qpel22_8bit, inter8xH_qpel23_8bit,
+		inter8xH_qpel30_8bit, inter8xH_qpel31_8bit, inter8xH_qpel32_8bit, inter8xH_qpel33_8bit,
+		inter16xH_qpel00_8bit, inter16xH_qpel01_8bit, inter16xH_qpel02_8bit, inter16xH_qpel03_8bit,
+		inter16xH_qpel10_8bit, inter16xH_qpel11_8bit, inter16xH_qpel12_8bit, inter16xH_qpel13_8bit,
+		inter16xH_qpel20_8bit, inter16xH_qpel21_8bit, inter16xH_qpel22_8bit, inter16xH_qpel23_8bit,
+		inter16xH_qpel30_8bit, inter16xH_qpel31_8bit, inter16xH_qpel32_8bit, inter16xH_qpel33_8bit,
+	};
+
 	size_t sstride_Y = ctx->stride_Y;
 	int xInt_Y = ctx->frame_offsets_x[i] + (x >> 2); // FIXME 16 bit
 	int yInt_Y = ctx->frame_offsets_y[i] + (y >> 2) * sstride_Y;
@@ -1192,59 +1207,8 @@
 	}

 	size_t dstride_Y = ctx->stride_Y;
-	switch ((w == 4 ? 0 : w == 8 ? 16 : 32) + yFrac_Y * 4 + xFrac_Y) {
-	case 0: CALL(inter4xH_qpel00_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 1: CALL(inter4xH_qpel01_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 2: CALL(inter4xH_qpel02_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 3: CALL(inter4xH_qpel03_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 4: CALL(inter4xH_qpel10_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 5: CALL(inter4xH_qpel11_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 6: CALL(inter4xH_qpel12_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 7: CALL(inter4xH_qpel13_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 8: CALL(inter4xH_qpel20_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 9: CALL(inter4xH_qpel21_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 10: CALL(inter4xH_qpel22_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 11: CALL(inter4xH_qpel23_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 12: CALL(inter4xH_qpel30_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 13: CALL(inter4xH_qpel31_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 14: CALL(inter4xH_qpel32_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 15: CALL(inter4xH_qpel33_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-
-	case 16: CALL(inter8xH_qpel00_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 17: CALL(inter8xH_qpel01_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 18: CALL(inter8xH_qpel02_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 19: CALL(inter8xH_qpel03_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 20: CALL(inter8xH_qpel10_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 21: CALL(inter8xH_qpel11_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 22: CALL(inter8xH_qpel12_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 23: CALL(inter8xH_qpel13_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 24: CALL(inter8xH_qpel20_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 25: CALL(inter8xH_qpel21_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 26: CALL(inter8xH_qpel22_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 27: CALL(inter8xH_qpel23_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 28: CALL(inter8xH_qpel30_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 29: CALL(inter8xH_qpel31_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 30: CALL(inter8xH_qpel32_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 31: CALL(inter8xH_qpel33_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-
-	case 32: CALL(inter16xH_qpel00_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 33: CALL(inter16xH_qpel01_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 34: CALL(inter16xH_qpel02_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 35: CALL(inter16xH_qpel03_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 36: CALL(inter16xH_qpel10_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 37: CALL(inter16xH_qpel11_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 38: CALL(inter16xH_qpel12_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 39: CALL(inter16xH_qpel13_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 40: CALL(inter16xH_qpel20_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 41: CALL(inter16xH_qpel21_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 42: CALL(inter16xH_qpel22_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 43: CALL(inter16xH_qpel23_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 44: CALL(inter16xH_qpel30_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 45: CALL(inter16xH_qpel31_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 46: CALL(inter16xH_qpel32_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	case 47: CALL(inter16xH_qpel33_8bit, h, dstride_Y, dst_Y, sstride_Y, src_Y); break;
-	default: __builtin_unreachable();
-	}
+	CALL(luma_fcts[(w == 4 ? 0 : w == 8 ? 16 : 32) + yFrac_Y * 4 + xFrac_Y],
+		h, dstride_Y, dst_Y, sstride_Y, src_Y);

 	// temporary hardcoding 4:2:0 until devising a simpler internal plane storage
 	size_t sstride_C = ctx->stride_C;


[core] Y2038: error log high-precision timestamps

fix struct type used for error log high-precision timestamps
(difference is only for 32-bit)

--- src/log.c
+++ src/log.c
@@ -100,7 +100,7 @@
 log_buffer_timestamp (buffer * const restrict b)
 {
     if (-2 == log_tlast) { /* -2 is value to flag high-precision timestamp */
-        struct timespec ts = { 0, 0 };
+        unix_timespec64_t ts = { 0, 0 };
         log_clock_gettime_realtime(&ts);
       #if 0
         buffer_append_int(b, TIME64_CAST(ts.tv_sec));


Bug fixes in Inter

Bug fixes in Inter

--- edge264_inter_ssse3.c
+++ edge264_inter_ssse3.c
@@ -1,10 +1,8 @@
 // TODO: Reload values from memory in 8x8 to prevent spills
 // TODO: Add pmadd weighting in the functions
 // TODO: initialize zero in each function since clang prefers
-// TODO: stop using lddqu (very slow on Atom and a bit slower in all)
 // TODO: in filter_36tapD_8bit, see if we can remove the last shift right by more aggressive previous shifts
 // TODO: allow reads past buffer on condition that 16 bytes are allocated past buffer ?
-// TODO: optimize INTER4x4_QPEL_21_22_23
 // TODO: see if there are many unpacklo(.., zero) that need a function for movzx

 #include "edge264_common.h"
@@ -729,9 +727,9 @@
 	int inter16x16_ ## QPEL ## _8bit(__m128i zero, size_t stride, ssize_t nstride, uint8_t *p, size_t dstStride, __m128i *dst) {\
 		__m128i d00 = _mm_lddqu_si128((__m128i *)(p + nstride * 2));\
 		__m128i d10 = _mm_lddqu_si128((__m128i *)(p + nstride    ));\
-		__m128i d20 = _mm_lddqu_si128((__m128i *)(p + nstride * 2));\
-		__m128i d30 = _mm_lddqu_si128((__m128i *)(p + nstride * 2));\
-		__m128i d40 = _mm_lddqu_si128((__m128i *)(p + nstride * 2));\
+		__m128i d20 = _mm_lddqu_si128((__m128i *)(p              ));\
+		__m128i d30 = _mm_lddqu_si128((__m128i *)(p +  stride    ));\
+		__m128i d40 = _mm_lddqu_si128((__m128i *)(p +  stride * 2));\
 		__m128i l00 = _mm_unpacklo_epi8(d00, zero);\
 		__m128i l08 = _mm_unpackhi_epi8(d00, zero);\
 		__m128i l10 = _mm_unpacklo_epi8(d10, zero);\
@@ -913,6 +911,7 @@
 INTER16x16_QPEL_21_23(qpel21, packus_6tapD_8bit(v02, v0A, vh, zero))
 INTER16x16_QPEL_21_23(qpel23, packus_6tapD_8bit(v03, v0B, vh, zero))

+// with an array on stack or a preliminary loop, both compilers get crazy
 #define INTER16x16_QPEL_12_22_32(QPEL, P)\
 	int inter16x16_ ## QPEL ## _8bit(__m128i zero, size_t stride, ssize_t nstride, uint8_t *p, size_t dstStride, __m128i *dst) {\
 		__m128i d00 = _mm_lddqu_si128((__m128i *)(p + nstride * 2 - 2));\


Adding the log string for ERR_LVL that was missing

--- src/log.c
+++ src/log.c
@@ -51,6 +51,9 @@
         case WARN_LVL:
             loglvl_str = "WARN";
             break ;
+        case ERR_LVL:
+            loglvl_str = "ERR";
+            break ;
         default:
             break ;
         }


Prevent recursive log calls

Prevent recursive log calls

--- src/log.c
+++ src/log.c
@@ -26,10 +26,15 @@

 int u_log(int level, char* fmt, ...)
 {
+	static bool logging = false;
 	struct tm *tm;
 	char tmbuf[512];
 	char buf[BUFSIZE];
 	va_list va;
+
+	if (logging)
+		return 0;
+	logging = true;

 	if (level > u_log_level)
 		return 0;
@@ -49,6 +54,8 @@
 	hook.line = buf;
 	u_hook_call(HOOK_LOG, &hook);

+	logging = false;
+
 	return u_log_handler(level, tmbuf, buf);
 }


Improve a way how log backends are switched.

--- src/log.c
+++ src/log.c
@@ -133,8 +133,7 @@

 void ft_log_backend_switch(struct ft_log_backend * backend)
 {
-	if ((ft_config.log_backend != NULL) && (ft_config.log_backend->fini != NULL))
-		ft_config.log_backend->fini();
+	struct ft_log_backend * old_backend = ft_config.log_backend;

 	if (backend == NULL)
 	{
@@ -142,6 +141,9 @@
 	}

 	ft_config.log_backend = backend;
+
+	if ((old_backend != NULL) && (old_backend->fini != NULL))
+		old_backend->fini();
 }


log BUGFIX always use module names, never submodule

--- src/log.c
+++ src/log.c
@@ -517,11 +517,11 @@
                             len = strlen(diter->schema->name);
                             (*index) -= len;
                             memcpy(&path[(*index)], diter->schema->name, len);
-                            if (prefix_all || (dlist->schema->module != diter->schema->module)) {
+                            if (prefix_all || (lyd_node_module(dlist) != lyd_node_module(diter))) {
                                 path[--(*index)] = ':';
-                                len = strlen(diter->schema->module->name);
+                                len = strlen(lyd_node_module(diter)->name);
                                 (*index) -= len;
-                                memcpy(&path[(*index)], diter->schema->module->name, len);
+                                memcpy(&path[(*index)], lyd_node_module(diter)->name, len);
                             }
                             path[--(*index)] = '[';
                         }


log: disable the non-buffered logging YAZ-780

This makes yaz_log on regular files make one write per line rather
than one write per fprintf call.

--- src/log.c
+++ src/log.c
@@ -340,8 +340,6 @@
         {
             yaz_log_close();
             yaz_log_info.log_file = new_file;
-            if (l_level & YLOG_FLUSH)
-                setvbuf(yaz_log_info.log_file, 0, _IONBF, 0);
         }
         else
         {


utils: log ring now correctly defaults to 0.


remove using std from header

remove using std from header

--- src/log.h
+++ src/log.h
@@ -4,56 +4,54 @@
 #include <vector>
 #include <memory>

-using namespace std;
+    namespace raft {
+    struct LogEntry {
+      unsigned int term;
+  // TODO   void* data;
+    };

-namespace raft {
-  struct LogEntry {
-    unsigned int term;
-// TODO   void* data;
-  };
+    class Log {
+      public:
+        Log() {};
+        virtual ~Log() {};

-  class Log {
-    public:
-      Log() {};
-      virtual ~Log() {};
+        // the return value is available as long as the Log alive
+        virtual const LogEntry* GetLastEntry() const = 0;
+        virtual const LogEntry* Get(unsigned int index) const = 0;
+        virtual unsigned int Size() const = 0;
+        virtual void Append(const LogEntry& entry) = 0;
+        virtual void Trim(unsigned int index) = 0;
+      private:
+        Log(Log&);
+        Log& operator=(const Log&);
+    };

-      // the return value is available as long as the Log alive
-      virtual const LogEntry* GetLastEntry() const = 0;
-      virtual const LogEntry* Get(unsigned int index) const = 0;
-      virtual unsigned int Size() const = 0;
-      virtual void Append(const LogEntry& entry) = 0;
-      virtual void Trim(unsigned int index) = 0;
-    private:
-      Log(Log&);
-      Log& operator=(const Log&);
-  };
-
-  class InMemoryLog : public Log {
-    public:
-      InMemoryLog() {};
-      const LogEntry* GetLastEntry() const {
-        return entries_.empty()
-          ? nullptr
-          : entries_.back().get();
-      };
-      const LogEntry* Get(unsigned int index) const {
-        return entries_.size() <= index
-          ? nullptr
-          : entries_[index].get();
-      }
-      virtual unsigned int Size() const {
-        return entries_.size();
-      }
-      void Append(const LogEntry& entry) {
-        auto e = unique_ptr<LogEntry>(new LogEntry(entry));
-        entries_.push_back(move(e));
-      }
-      void Trim(unsigned int index) {
-        entries_.erase(entries_.begin() + index, entries_.end());
-      }
-      virtual ~InMemoryLog() { };
-    private:
-      vector<unique_ptr<LogEntry>> entries_;
-  };
-}
+    class InMemoryLog : public Log {
+      public:
+        InMemoryLog() {};
+        const LogEntry* GetLastEntry() const {
+          return entries_.empty()
+            ? nullptr
+            : entries_.back().get();
+        };
+        const LogEntry* Get(unsigned int index) const {
+          return entries_.size() <= index
+            ? nullptr
+            : entries_[index].get();
+        }
+        virtual unsigned int Size() const {
+          return entries_.size();
+        }
+        void Append(const LogEntry& entry) {
+          auto e = std::unique_ptr<LogEntry>(new LogEntry(entry));
+          entries_.push_back(move(e));
+        }
+        void Trim(unsigned int index) {
+          entries_.erase(entries_.begin() + index, entries_.end());
+        }
+        virtual ~InMemoryLog() { };
+      private:
+        std::vector<std::unique_ptr<LogEntry>> entries_;
+    };
+  }
 #endif


Add comments to logging macros.

Add comments to logging macros.

--- src/log.h
+++ src/log.h
@@ -10,24 +10,33 @@
 #include <errno.h>
 #include <string.h>

+/** Prints a debug message if not compiled with NDEBUG. */
 #ifdef NDEBUG
 #define debug(M, ...)
 #else
 #define debug(M, ...) fprintf(stderr, "DEBUG %s:%d: " M "\n", __FILE__, __LINE__, ##__VA_ARGS__)
 #endif

+/** Returns errno as a string if its set. */
 #define clean_errno() (errno == 0 ? "None" : strerror(errno))

+/** Writes an error message to stderr. */
 #define log_err(M, ...) fprintf(stderr, "[ERROR] (%s:%d: errno: %s) " M "\n", __FILE__, __LINE__, clean_errno(), ##__VA_ARGS__)

+/** Writes a warning message to stderr. */
 #define log_warn(M, ...) fprintf(stderr, "[WARN] (%s:%d: errno: %s) " M "\n", __FILE__, __LINE__, clean_errno(), ##__VA_ARGS__)

+/** Writes an information message to stderr. */
 #define log_info(M, ...) fprintf(stderr, "[INFO] (%s:%d) " M "\n", __FILE__, __LINE__, ##__VA_ARGS__)

+/** Checks the condition A, logs and jumps to error label on error. */
 #define check(A, M, ...) if(!(A)) { log_err(M, ##__VA_ARGS__); errno=0; goto error; }

+/** Marks code that should not run.  If it does, log and jump to error. */
 #define sentinel(M, ...)  { log_err(M, ##__VA_ARGS__); errno=0; goto error; }

+/** Check that A is not null, else log and jump to error. */
 #define check_mem(A) check((A), "Out of memory.")

+/** Same as check, but doesn't print if NDEBUG is set. */
 #define check_debug(A, M, ...) if(!(A)) { debug(M, ##__VA_ARGS__); errno=0; goto error; }


work updates

work updates

--- src/lr4.c
+++ src/lr4.c
@@ -635,12 +635,15 @@
 				fprintf(header, "DNUM 0x%X\nDSIZE 0x%X\n", datasizes[i].num, datasizes[i].size);
 			}
 			/* If N_DEFINED is 1, put the information for the low level assembler. Allocate 13 plus a little extra... should be enough!*/
-			nstartstr = calloc(1, 20);
-			N_ = calloc(1, 4);
-			memcpy(N_, "N_", 4);
-			sprintf(nstartstr, "NSTART %s\n", findreplace(N_, replaces, numreplaces, 0, 0));
-			fputs(nstartstr, header);
-			free(nstartstr);
+			if(N_DEFINED)
+			{
+				nstartstr = calloc(1, 20);
+				N_ = calloc(1, 4);
+				memcpy(N_, "N_", 4);
+				sprintf(nstartstr, "NSTART %s\n", findreplace(N_, replaces, numreplaces, 0, 0));
+				fputs(nstartstr, header);
+				free(nstartstr);
+			}
 			/* End of the header */
 			fputs("EINF\n", header);
 			/* Instead of making an internal buffer, move the header file to the name of the output file and append the rest of the assembly below it. */
@@ -672,11 +675,50 @@
 			if(numdatasizes == 0)
 			{
 				fputs("D_SEC:", header);
-				puts("huh?");
 			}
 			fclose(header);
 		}
-
+		/* Make sure to print the N_ if it is defined. This also cleans whitespace... */
+		/* This is not the cleanest code to prepend the NSTART, and should probably be combined with the above case. */
+		else
+		{
+			char *nstartstr = NULL;
+			char *N_ = NULL;
+
+			fclose(outasm);
+			fclose(header);
+			remove("texttemp");
+			rename(argv[3], "texttemp");
+			outasm = fopen("texttemp", "r");
+			header = fopen(argv[3], "a");
+			if(N_DEFINED)
+			{
+				nstartstr = calloc(1, 20);
+				N_ = calloc(1, 4);
+				memcpy(N_, "N_", 4);
+				sprintf(nstartstr, "NSTART %s\n", findreplace(N_, replaces, numreplaces, 0, 0));
+				fputs(nstartstr, header);
+				free(nstartstr);
+			}
+			free(line);
+			line = NULL;
+			len = 0;
+			linelen = getline(&line, &len, outasm);
+			/* Copy every line one by one */
+			while(linelen > -1)
+			{
+				/* If it starts with a space, it's likely an empty line so skip it. */
+				if(!isspace((unsigned char)line[0]))
+				{
+					fputs(line, header);
+				}
+				free(line);
+				line = NULL;
+				len = 0;
+				linelen = getline(&line, &len, outasm);
+			}
+			fclose(header);
+		}
 		/* Free the list of replacements and close all the files - we're done our work here. */
 		for(i = 0; i < numreplaces; i++)
 		{


LRU without catching std::range_error

LRU without catching std::range_error

--- src/lru.h
+++ src/lru.h
@@ -75,6 +75,22 @@
 		return _items_list.cend();
 	}

+	auto find(const Key& key) {
+		auto it(_items_map.find(key));
+		if (it == _items_map.end()) {
+			return _items_list.end();
+		}
+		return it->second;
+	}
+
+	auto find(const Key& key) const {
+		auto it(_items_map.find(key));
+		if (it == _items_map.cend()) {
+			return _items_list.cend();
+		}
+		return it->second;
+	}
+
 	LRU(ssize_t max_size=-1) : _max_size(max_size) { }

 	size_t erase(const Key& key) {
@@ -113,22 +129,25 @@
 		return insert(std::make_pair(std::forward<Args>(args)...));
 	}

+	T& at(const iterator& it) {
+		_items_list.splice(_items_list.begin(), _items_list, it);
+		return it->second;
+	}
+
 	T& at(const Key& key) {
 		auto it(_items_map.find(key));
 		if (it == _items_map.end()) {
 			throw std::range_error("There is no such key in cache");
 		}
-
-		_items_list.splice(_items_list.begin(), _items_list, it->second);
-		return it->second->second;
+		return at(it->second);
 	}

 	T& get(const Key& key) {
-		try {
-			return at(key);
-		} catch (const std::range_error&) {
+		auto it(_items_map.find(key));
+		if (it == _items_map.end()) {
 			return insert(std::make_pair(key, T()));
 		}
+		return at(it->second);
 	}

 	T& operator[] (const Key& key) {
@@ -192,28 +211,31 @@
 	}

 	template<typename OnGet>
-	T& at_and(const OnGet& on_get, const Key& key) {
-		auto it(_items_map.find(key));
-		if (it == _items_map.end()) {
-			throw std::range_error("There is no such key in cache");
-		}
-
-		T& ref = it->second->second;
+	T& at_and(const OnGet& on_get, const iterator& it) {
+		T& ref = it->second;
 		switch (on_get(ref)) {
 			case GetAction::leave:
 				break;
 			case GetAction::renew:
-				_items_list.splice(_items_list.begin(), _items_list, it->second);
+				_items_list.splice(_items_list.begin(), _items_list, it);
 				break;
 		}
 		return ref;
+	}
+
+	template<typename OnGet>
+	T& at_and(const OnGet& on_get, const Key& key) {
+		auto it(_items_map.find(key));
+		if (it == _items_map.end()) {
+			throw std::range_error("There is no such key in cache");
+		}
+		return at_and(on_get, it->second);
 	}

 	template<typename OnGet>
 	T& get_and(const OnGet& on_get, const Key& key) {
-		try {
-			return at_and(on_get, key);
-		} catch (const std::range_error&) {
+		auto it(_items_map.find(key));
+		if (it == _items_map.end()) {
 			T& ref = insert(std::make_pair(key, T()));
 			switch (on_get(ref)) {
 				case GetAction::leave:
@@ -223,7 +245,8 @@
 			}
 			return ref;
 		}
-	}
-};
-
-};
+		return at_and(on_get, it->second);
+	}
+};
+
+};


Allow passing constructor parameters to default type in get()

--- src/lru.h
+++ src/lru.h
@@ -186,10 +186,11 @@
 		return at(m_it->second);
 	}

-	T& get(const Key& key) {
-		auto m_it(_items_map.find(key));
-		if (m_it == _items_map.end()) {
-			return insert(std::make_pair(key, T())).first->second;
+	template<typename... Args>
+	T& get(const Key& key, Args&&... args) {
+		auto m_it(_items_map.find(key));
+		if (m_it == _items_map.end()) {
+			return emplace(key, T(std::forward<Args>(args)...)).first->second;
 		}
 		return at(m_it->second);
 	}
@@ -320,11 +321,11 @@
 		return at_and(on_get, m_it->second);
 	}

-	template<typename OnGet>
-	T& get_and(const OnGet& on_get, const Key& key) {
-		auto m_it(_items_map.find(key));
-		if (m_it == _items_map.end()) {
-			T& ref = insert(std::make_pair(key, T())).first->second;
+	template<typename OnGet, typename... Args>
+	T& get_and(const OnGet& on_get, const Key& key, Args&&... args) {
+		auto m_it(_items_map.find(key));
+		if (m_it == _items_map.end()) {
+			T& ref = emplace(key, T(std::forward<Args>(args)...)).first->second;
 			switch (on_get(ref)) {
 				case GetAction::leave:
 					break;


Fix memory leak in map implementation

Fix memory leak in map implementation

This commit fixes a (rather nasty) memory leak in the map
implementation. The free function for this module failed to free the
memory allocated for each bucket of the hash table.

--- src/map.c
+++ src/map.c
@@ -208,6 +208,8 @@

         res = list_free(handle_free, bucket);
         PASS_UP_ON_FAIL(res);
+
+        free(bucket);
     }

     res = list_free(NULL, map->buckets);


Fix Mat_VarDelete

Fix Mat_VarDelete

Move matvar two levels down

--- src/mat.c
+++ src/mat.c
@@ -749,7 +749,6 @@
     char *tmp_name, *new_name;
     char temp[7] = "XXXXXX";
     mat_t *tmp;
-    matvar_t *matvar;

     if ( NULL == mat || NULL == name )
         return err;
@@ -770,6 +769,7 @@
     if (tmp_name != NULL) {
         tmp      = Mat_CreateVer(tmp_name,mat->header,mat_file_ver);
         if ( tmp != NULL ) {
+            matvar_t *matvar;
             while ( NULL != (matvar = Mat_VarReadNext(mat)) ) {
                 if ( strcmp(matvar->name,name) )
                     Mat_VarWrite(tmp,matvar,0);


Add arg_lookup

Add arg_lookup

--- src/mem.h
+++ src/mem.h
@@ -56,6 +56,7 @@
 extern void arg_insert(struct _object_t *sym, struct _object_t *val);
 extern struct bind_tree *env_lookup_node(object_t *symbol);
 extern struct _object_t *env_lookup(struct _object_t *sym);
+extern struct _object_t *arg_lookup(struct _object_t *sym);
 extern void gc();
 extern void mark();


let KORE_MSG_WORKER_ALL include sender.

let KORE_MSG_WORKER_ALL include sender.

--- src/msg.c
+++ src/msg.c
@@ -181,8 +181,6 @@
 	if (worker == NULL && type == NULL) {
 		destination = msg->dst;
 		TAILQ_FOREACH(c, &connections, list) {
-			if (c == nb->owner)
-				continue;
 			if (c->proto != CONN_PROTO_MSG || c->hdlr_extra == NULL)
 				continue;


Fix potential invalid memory access

Fix potential invalid memory access

This patch fixes a potential memory access when registering a new
device. PDU must include at least one character representing the
device name.

--- src/msg.c
+++ src/msg.c
@@ -984,9 +984,9 @@
 }

 static int8_t msg_register(int sock, int proto_sock,
-					const struct proto_ops *proto_ops,
-					const knot_msg_register *kreq,
-					knot_msg_credential *krsp)
+			   const struct proto_ops *proto_ops,
+			   const knot_msg_register *kreq, size_t ilen,
+			   knot_msg_credential *krsp)
 {
 	GIOChannel *io, *proto_io;
 	struct trust *trust;
@@ -1000,6 +1000,12 @@
 	struct proto_watch *proto_watch;
 	socklen_t sklen;
 	struct ucred cred;
+
+	/* Min PDU len containing at least one char representing name */
+	if (ilen <= (sizeof(kreq->hdr) + sizeof(kreq->id))) {
+		hal_log_error("Missing device name!");
+		return KNOT_REGISTER_INVALID_DEVICENAME;
+	}

 	/*
 	 * Credential (Process ID) verification will work for unix socket
@@ -1788,7 +1794,7 @@
 	case KNOT_MSG_REGISTER_REQ:
 		/* Payload length is set by the caller */
 		result = msg_register(sock, proto_sock, proto_ops,
-						&kreq->reg, &krsp->cred);
+				      &kreq->reg, ilen, &krsp->cred);
 		rtype = KNOT_MSG_REGISTER_RESP;
 		break;
 	case KNOT_MSG_UNREGISTER_REQ:


Removed variant forward declaration.

Removed variant forward declaration.

--- src/mud.h
+++ src/mud.h
@@ -33,7 +33,6 @@
 */
 //forward declarations
 //I wanted to avoid these, but it seems I have no choice
-class Entity;
 class Socket;
 class Player;
 class Component;
@@ -41,7 +40,6 @@
 class StaticObject;
 class Zone;
 class Room;
-class ObjectManager;

 //olc forward declarations
 struct OLC_DATA;


net: Implement veth net model

net: Implement veth net model

It's perfrctly possible to create veth with peer end right in
the target pid namespace. One only need to properly prepare the
netlink message.

Signed-off-by: Pavel Emelyanov <c9a32589e048e044184536f7ac71ef92fe82df3e@parallels.com>

--- src/net.c
+++ src/net.c
@@ -18,7 +18,7 @@
  * Move network device @name into task's @pid net namespace
  */

-int net_nic_move(char *name, int pid)
+static int net_nic_move(char *name, int pid)
 {
 	struct nlmsghdr *h;
 	struct ifinfomsg *ifi;
@@ -60,13 +60,78 @@
  * VETH creation/removal
  */

-int veth_pair_create(struct ct_net_veth_arg *va)
-{
-	return -1;
-}
-
-void veth_pair_destroy(struct ct_net_veth_arg *va)
-{
+#ifndef VETH_INFO_MAX
+enum {
+	VETH_INFO_UNSPEC,
+	VETH_INFO_PEER,
+
+	__VETH_INFO_MAX
+#define VETH_INFO_MAX   (__VETH_INFO_MAX - 1)
+};
+#endif
+
+static int veth_pair_create(struct ct_net_veth_arg *va, int ct_pid)
+{
+	struct nlmsghdr *h;
+	struct ifinfomsg *ifi;
+	struct rtattr *linfo, *data, *peer;
+	int nlfd, err;
+
+	/*
+	 * FIXME -- one nlconn per container/session
+	 */
+
+	err = nlfd = netlink_open(NETLINK_ROUTE);
+	if (nlfd < 0)
+		goto err_o;
+
+	err = -1;
+	h = nlmsg_alloc(sizeof(struct ifinfomsg));
+	if (!h)
+		goto err_a;
+
+	h->nlmsg_type = RTM_NEWLINK;
+	h->nlmsg_flags = NLM_F_REQUEST|NLM_F_ACK|NLM_F_CREATE;
+	ifi = (struct ifinfomsg *)(h + 1);
+	ifi->ifi_family = AF_UNSPEC;
+	ifi->ifi_index = 0;
+	if (nla_put_string(h, IFLA_IFNAME, va->host_name))
+		goto err;
+
+	linfo = nla_put_nested(h, IFLA_LINKINFO);
+	if (!linfo)
+		goto err;
+
+	if (nla_put_string(h, IFLA_INFO_KIND, "veth"))
+		goto err;
+
+	data = nla_put_nested(h, IFLA_INFO_DATA);
+	if (!data)
+		goto err;
+
+	peer = nla_put_nested(h, VETH_INFO_PEER);
+	if (!peer)
+		goto err;
+
+	h->nlmsg_len += sizeof(struct ifinfomsg);
+
+	if (nla_put_string(h, IFLA_IFNAME, va->ct_name))
+		goto err;
+
+	if (nla_put_u32(h, IFLA_NET_NS_PID, ct_pid))
+		goto err;
+
+	nla_commit_nested(h, peer);
+	nla_commit_nested(h, data);
+	nla_commit_nested(h, linfo);
+
+	err = netlink_talk(nlfd, h, h);
+err:
+	nlmsg_free(h);
+err_a:
+	netlink_close(nlfd);
+err_o:
+	return err;
 }

 /*
@@ -255,33 +320,19 @@
 {
 	struct ct_net_veth *vn = cn2vn(n);

-	/*
-	 * FIXME -- the ct_name may be busy on host. Need to
-	 * create peer right in the target netns (IFLA_NET_NS_FD)
-	 */
-
-	if (veth_pair_create(&vn->v))
-		return -1;
-
-	if (net_nic_move(vn->v.ct_name, ct->root_pid)) {
-		veth_pair_destroy(&vn->v);
-		return -1;
-	}
+	if (veth_pair_create(&vn->v, ct->root_pid))
+		return -1;

 	return 0;
 }

 static void veth_stop(struct container *ct, struct ct_net *n)
 {
-	struct ct_net_veth *vn = cn2vn(n);
-
 	/*
 	 * FIXME -- don't destroy veth here, keep it across
 	 * container's restarts. This needs checks in the
 	 * veth_pair_create() for existance.
 	 */
-
-	veth_pair_destroy(&vn->v);
 }

 static void veth_pack(void *arg, NetaddReq *req)


Set relative time t to zero when it expired

Not seting that relative time to zero will only (in the pop process) increase the next node relative time with this one.
e.g. if node1->t = 1000 (1 sec), and node2->t = 1000 ( + 1 sec),
after 1 sec, we pop node1 and node2 become first with t = 2000 (as pop will do node2->t += node1->t. But in reality, 1 second already elapsed, so node2->t should be 1000 instead.

--- src/net.c
+++ src/net.c
@@ -1998,6 +1998,7 @@
       break;
     } else {
       elapsed -= nextinqueue->t;
+      nextinqueue->t = 0;
       coap_retransmit(ctx, coap_pop_next(ctx));
       nextinqueue = coap_peek_next(ctx);
     }


Add override/final modifiers to V1TransportDeserializer

Summary:
Completes backport (7/7) of core [[https://github.com/bitcoin/bitcoin/pull/16202 | PR16202]]:
https://github.com/bitcoin/bitcoin/pull/16202/commits/ed2dc5e48abed1cde6ab98025dc8212917d47d21

Depends on D8227.

Test Plan:
  ninja all check-all

Reviewers: #bitcoin_abc, PiRK, jasonbcox

Reviewed By: #bitcoin_abc, PiRK, jasonbcox

Differential Revision: https://reviews.bitcoinabc.org/D8228

--- src/net.h
+++ src/net.h
@@ -692,7 +692,7 @@
     virtual ~TransportDeserializer() {}
 };

-class V1TransportDeserializer : public TransportDeserializer {
+class V1TransportDeserializer final : public TransportDeserializer {
 private:
     mutable CHash256 hasher;
     mutable uint256 data_hash;
@@ -732,7 +732,7 @@
         Reset();
     }

-    bool Complete() const {
+    bool Complete() const override {
         if (!in_data) {
             return false;
         }
@@ -740,11 +740,11 @@
         return (hdr.nMessageSize == nDataPos);
     }

-    void SetVersion(int nVersionIn) {
+    void SetVersion(int nVersionIn) override {
         hdrbuf.SetVersion(nVersionIn);
         vRecv.SetVersion(nVersionIn);
     }
-    int Read(const Config &config, const char *pch, uint32_t nBytes) {
+    int Read(const Config &config, const char *pch, uint32_t nBytes) override {
         int ret =
             in_data ? readData(pch, nBytes) : readHeader(config, pch, nBytes);
         if (ret < 0) {
@@ -753,7 +753,7 @@
         return ret;
     }

-    CNetMessage GetMessage(const Config &config, int64_t time);
+    CNetMessage GetMessage(const Config &config, int64_t time) override;
 };

 /** Information about a peer */


Version bump.

Version bump.

--- src/njs.h
+++ src/njs.h
@@ -11,7 +11,7 @@

 #include <njs_auto_config.h>

-#define NJS_VERSION                 "0.5.0"
+#define NJS_VERSION                 "0.5.1"

 #include <unistd.h>                 /* STDOUT_FILENO, STDERR_FILENO */


service: set one exit point (v2)

service: set one exit point (v2)

v2: remove exit()

Cc: Ruslan Kuprieiev <f6538312ce47017d734b1357aabc970ebf896e32@gmail.com>
Signed-off-by: Andrey Vagin <74c05afa918858348d6db8037d82fa8124870113@openvz.org>
Signed-off-by: Pavel Emelyanov <c9a32589e048e044184536f7ac71ef92fe82df3e@parallels.com>

--- cr-service.c
+++ cr-service.c
@@ -206,7 +206,7 @@

 int cr_service(bool daemon_mode)
 {
-	int server_fd;
+	int server_fd = -1;
 	int child_pid;

 	struct sockaddr_un server_addr;
@@ -220,7 +220,7 @@
 	server_fd = socket(AF_LOCAL, SOCK_SEQPACKET, 0);
 	if (server_fd == -1) {
 		pr_perror("Can't initialize service socket.");
-		return -1;
+		goto err;
 	}

 	memset(&server_addr, 0, sizeof(server_addr));
@@ -241,7 +241,7 @@
 	if (bind(server_fd, (struct sockaddr *) &server_addr,
 					server_addr_len) == -1) {
 		pr_perror("Can't bind.");
-		return -1;
+		goto err;
 	}

 	pr_info("The service socket is bound to %s\n", server_addr.sun_path);
@@ -249,18 +249,18 @@
 	/* change service socket permissions, so anyone can connect to it */
 	if (chmod(server_addr.sun_path, 0666)) {
 		pr_perror("Can't change permissions of the service socket.");
-		return -1;
+		goto err;
 	}

 	if (listen(server_fd, 16) == -1) {
 		pr_perror("Can't listen for socket connections.");
-		return -1;
+		goto err;
 	}

 	if (daemon_mode) {
 		if (daemon(1, 1) == -1) {
 			pr_perror("Can't run service server in the background");
-			return -errno;
+			goto err;
 		}
 	}

@@ -299,5 +299,8 @@
 		}
 	}

-	return 0;
-}
+err:
+	close_safe(&server_fd);
+
+	return 1;
+}


Bump API to 0.7.0.

Bump API to 0.7.0.

--- src/nng.h
+++ src/nng.h
@@ -48,7 +48,7 @@
 // version 0, you should not be making any forward compatibility
 // assumptions.
 #define NNG_MAJOR_VERSION 0
-#define NNG_MINOR_VERSION 5
+#define NNG_MINOR_VERSION 7
 #define NNG_PATCH_VERSION 0

 // Types common to nng.


Fix min columns

Fix min columns

--- src/nnn.c
+++ src/nnn.c
@@ -5758,7 +5758,7 @@
 	move_cursor(cur, 1);

 	/* Fail redraw if < than 10 columns, context info prints 10 chars */
-	if (ncols < MIN_DISPLAY_COLS) {
+	if (ncols <= MIN_DISPLAY_COLS) {
 		printmsg(messages[MSG_FEW_COLUMNS]);
 		return;
 	}


Use pipes.sh as fallback user lock

Use pipes.sh as fallback user lock

--- src/nnn.c
+++ src/nnn.c
@@ -333,8 +333,9 @@
 #define ATOOL 3
 #define BSDTAR 4
 #define LOCKER 5
-#define NLAUNCH 6
-#define UNKNOWN 7
+#define PIPES 6
+#define NLAUNCH 7
+#define UNKNOWN 8

 /* Utilities to open files, run actions */
 static char * const utils[] = {
@@ -356,6 +357,7 @@
 #else
 	"vlock",
 #endif
+	"pipes.sh",
 	"nlaunch",
 	"UNKNOWN"
 };
@@ -2605,6 +2607,15 @@
 	}

 	return TRUE;
+}
+
+static void lock_terminal(void)
+{
+	char *tmp = utils[LOCKER];
+	if (!getutil(tmp))
+		tmp = utils[PIPES];;
+
+	spawn(tmp, NULL, NULL, NULL, F_NORMAL);
 }

 /*
@@ -3724,7 +3735,7 @@
 				break;
 			}
 			default: /* SEL_LOCK */
-				spawn(utils[LOCKER], NULL, NULL, NULL, F_NORMAL);
+				lock_terminal();
 				break;
 			}

@@ -4252,11 +4263,7 @@
 			/* Locker */
 			if (idletimeout && idle == idletimeout) {
 				idle = 0;
-				tmp = utils[LOCKER];
-				if (!getutil(tmp))
-					tmp = "pipes.sh";
-
-				spawn(tmp, NULL, NULL, NULL, F_NORMAL);
+				lock_terminal();
 				if (ndents)
 					copycurname();
 				goto begin;