+ /* Leave data after the first line of the query in the buffer */
+ c->querybuf = sdsrange(c->querybuf,querylen+2,-1);
+
+ /* Setup argv array on client structure */
+ if (c->argv) zfree(c->argv);
+ c->argv = zmalloc(sizeof(robj*)*argc);
+
+ /* Create redis objects for all arguments. */
+ for (c->argc = 0, j = 0; j < argc; j++) {
+ if (sdslen(argv[j])) {
+ c->argv[c->argc] = createObject(REDIS_STRING,argv[j]);
+ c->argc++;
+ } else {
+ sdsfree(argv[j]);
+ }
+ }
+ zfree(argv);
+ return REDIS_OK;
+}
+
+/* Helper function. Trims query buffer to make the function that processes
+ * multi bulk requests idempotent. */
+static void setProtocolError(redisClient *c, int pos) {
+ c->flags |= REDIS_CLOSE_AFTER_REPLY;
+ c->querybuf = sdsrange(c->querybuf,pos,-1);
+}
+
+int processMultibulkBuffer(redisClient *c) {
+ char *newline = NULL;
+ char *eptr;
+ int pos = 0, tolerr;
+ long bulklen;
+
+ if (c->multibulklen == 0) {
+ /* The client should have been reset */
+ redisAssert(c->argc == 0);
+
+ /* Multi bulk length cannot be read without a \r\n */
+ newline = strstr(c->querybuf,"\r\n");
+ if (newline == NULL)
+ return REDIS_ERR;
+
+ /* We know for sure there is a whole line since newline != NULL,
+ * so go ahead and find out the multi bulk length. */
+ redisAssert(c->querybuf[0] == '*');
+ c->multibulklen = strtol(c->querybuf+1,&eptr,10);
+ pos = (newline-c->querybuf)+2;
+ if (c->multibulklen <= 0) {
+ c->querybuf = sdsrange(c->querybuf,pos,-1);
+ return REDIS_OK;
+ } else if (c->multibulklen > 1024*1024) {
+ addReplyError(c,"Protocol error: invalid multibulk length");
+ setProtocolError(c,pos);
+ return REDIS_ERR;
+ }
+
+ /* Setup argv array on client structure */
+ if (c->argv) zfree(c->argv);
+ c->argv = zmalloc(sizeof(robj*)*c->multibulklen);
+
+ /* Search new newline */
+ newline = strstr(c->querybuf+pos,"\r\n");
+ }
+
+ redisAssert(c->multibulklen > 0);
+ while(c->multibulklen) {
+ /* Read bulk length if unknown */
+ if (c->bulklen == -1) {
+ newline = strstr(c->querybuf+pos,"\r\n");
+ if (newline != NULL) {
+ if (c->querybuf[pos] != '$') {
+ addReplyErrorFormat(c,
+ "Protocol error: expected '$', got '%c'",
+ c->querybuf[pos]);
+ setProtocolError(c,pos);
+ return REDIS_ERR;
+ }
+
+ bulklen = strtol(c->querybuf+pos+1,&eptr,10);
+ tolerr = (eptr[0] != '\r');
+ if (tolerr || bulklen == LONG_MIN || bulklen == LONG_MAX ||
+ bulklen < 0 || bulklen > 512*1024*1024)
+ {
+ addReplyError(c,"Protocol error: invalid bulk length");
+ setProtocolError(c,pos);
+ return REDIS_ERR;