Example #1
0
int32_t
adts_list_prepend( adts_list_t      *p_adts_list,
                   adts_list_node_t *p_adts_list_node )
{
    return list_insert(p_adts_list, p_adts_list_node, LIST_PREPEND);
} /* adts_list_prepend() */
Example #2
0
ex_off_t _lru_attempt_free_mem(cache_t *c, segment_t *page_seg, ex_off_t bytes_to_free)
{
    cache_lru_t *cp = (cache_lru_t *)c->fn.priv;
    cache_segment_t *s;
    segment_t *pseg;
    cache_page_t *p;
    page_lru_t *lp;
    Stack_ele_t *ele;
    op_generic_t *gop;
    opque_t *q;
    ex_off_t total_bytes, freed_bytes, pending_bytes, *poff;
    ex_off_t *segid;
    ex_off_t min_off, max_off;
    list_iter_t sit;
    int count, bits, cw, flush_count;
    list_t *table;
    page_table_t *ptable;
    pigeon_coop_hole_t pch, pt_pch;

    log_printf(15, "START seg=" XIDT " bytes_to_free=" XOT " bytes_used=" XOT " stack_size=%d\n", segment_id(page_seg), bytes_to_free, cp->bytes_used, stack_size(cp->stack));

    freed_bytes = 0;
    pending_bytes = 0;
    total_bytes = 0;

    //** cache_lock(c) is already acquired
    pch = reserve_pigeon_coop_hole(cp->free_pending_tables);
    table = *(list_t **)pigeon_coop_hole_data(&pch);

    //** Get the list of pages to free
    move_to_bottom(cp->stack);
    ele = stack_unlink_current(cp->stack, 1);
    while ((total_bytes < bytes_to_free) && (ele != NULL)) {
        p = (cache_page_t *)get_stack_ele_data(ele);
        lp = (page_lru_t *)p->priv;

        bits = atomic_get(p->bit_fields);
        log_printf(15, "checking page for release seg=" XIDT " p->offset=" XOT " bits=%d\n", segment_id(p->seg), p->offset, bits);
        flush_log();

        if ((bits & C_TORELEASE) == 0) { //** Skip it if already flagged for removal
            ptable = (page_table_t *)list_search(table, (list_key_t *)&(segment_id(p->seg)));
            if (ptable == NULL) {  //** Have to make a new segment entry
                pt_pch = reserve_pigeon_coop_hole(cp->free_page_tables);
                ptable = (page_table_t *)pigeon_coop_hole_data(&pt_pch);
                ptable->seg = p->seg;
                ptable->id = segment_id(p->seg);
                ptable->pch = pt_pch;
                list_insert(table, &(ptable->id), ptable);
            }

            cp->limbo_pages++;
            log_printf(15, "UNLINKING seg=" XIDT " p->offset=" XOT " bits=%d limbo=%d\n", segment_id(p->seg), p->offset, bits, cp->limbo_pages);

            atomic_inc(p->access_pending[CACHE_READ]);  //** Do this so it's not accidentally deleted
            push(ptable->stack, p);
            s = (cache_segment_t *)p->seg->priv;
            total_bytes += s->page_size;
            free(lp->ele);
            lp->ele = NULL;  //** Mark it as removed from the list so a page_release doesn't free also
        }

        if (total_bytes < bytes_to_free) ele = stack_unlink_current(cp->stack, 1);
    }


    if (total_bytes == 0) {  //** Nothing to do so exit
        log_printf(15, "Nothing to do so exiting\n");
        release_pigeon_coop_hole(cp->free_pending_tables, &pch);
        return(0);
    }

    cache_unlock(c);  //** Don't need the cache lock for the next part

    q = new_opque();
    opque_start_execution(q);

    //** Now cycle through the segments to be freed
    pending_bytes = 0;
    sit = list_iter_search(table, list_first_key(table), 0);
    list_next(&sit, (list_key_t **)&segid, (list_data_t **)&ptable);
    while (ptable != NULL) {
        //** Verify the segment is still valid.  If not then just delete everything
        pseg = list_search(c->segments, segid);
        if (pseg != NULL) {
            segment_lock(ptable->seg);
            min_off = s->total_size;
            max_off = -1;

            s = (cache_segment_t *)ptable->seg->priv;
            while ((p = pop(ptable->stack)) != NULL) {
                atomic_dec(p->access_pending[CACHE_READ]); //** Removed my access control from earlier
                flush_count = atomic_get(p->access_pending[CACHE_FLUSH]);
                cw = atomic_get(p->access_pending[CACHE_WRITE]);
                count = atomic_get(p->access_pending[CACHE_READ]) + cw + flush_count;
                bits = atomic_get(p->bit_fields);
                if (count != 0) { //** Currently in use so wait for it to be released
                    if (cw > 0) {  //** Got writes so need to wait until they complete otherwise the page may not get released
                        bits = bits | C_TORELEASE;  //** Mark it for release
                        atomic_set(p->bit_fields, bits);
                        _cache_drain_writes(p->seg, p);  //** Drain the write ops
                        bits = atomic_get(p->bit_fields);  //** Get the bit fields to see if it's dirty
                    }

                    if (flush_count == 0) {  //** Make sure it's not already being flushed
                        if ((bits & C_ISDIRTY) != 0) {  //** Have to flush it don't have to track it cause the flush will do the release
                            if (min_off > p->offset) min_off = p->offset;
                            if (max_off < p->offset) max_off = p->offset;
                        }
                    }
                    bits = bits | C_TORELEASE;

                    log_printf(15, "in use tagging for release seg=" XIDT " p->offset=" XOT " bits=%d\n", segment_id(p->seg), p->offset, bits);
                    atomic_set(p->bit_fields, bits);

                    pending_bytes += s->page_size;
                } else {  //** Not in use
                    if ((bits & (C_ISDIRTY|C_EMPTY)) == 0) {  //** Don't have to flush it just drop the page
                        cp->limbo_pages--;
                        log_printf(15, "FREEING page seg=" XIDT " p->offset=" XOT " bits=%d limbo=%d\n", segment_id(p->seg), p->offset, bits, cp->limbo_pages);
                        list_remove(s->pages, &(p->offset), p);  //** Have to do this here cause p->offset is the key var
                        if (p->data[0].ptr) free(p->data[0].ptr);
                        if (p->data[1].ptr) free(p->data[1].ptr);
                        lp = (page_lru_t *)p->priv;
                        free(lp);
                        freed_bytes += s->page_size;
                    } else {         //** Got to flush the page first but don't have to track it cause the flush will do the release
                        if (p->offset > -1) { //** Skip blank pages
                            if (min_off > p->offset) min_off = p->offset;
                            if (max_off < p->offset) max_off = p->offset;
                        }

                        bits = bits | C_TORELEASE;
                        atomic_set(p->bit_fields, bits);

                        pending_bytes += s->page_size;
                        if (p->offset > -1) {
                            log_printf(15, "FLUSHING page seg=" XIDT " p->offset=" XOT " bits=%d\n", segment_id(p->seg), p->offset, bits);
                        } else {
                            log_printf(15, "RELEASE trigger for empty page seg=" XIDT " p->offset=" XOT " bits=%d\n", segment_id(p->seg), p->offset, bits);
                        }
                    }
                }

                list_next(&sit, (list_key_t **)&poff, (list_data_t **)&p);
            }

            segment_unlock(ptable->seg);

            if (max_off>-1) {
                gop = cache_flush_range(ptable->seg, s->c->da, min_off, max_off + s->page_size - 1, s->c->timeout);
                opque_add(q, gop);
            }
        } else {  //** Segment has been deleted so drop everything cause it's already freeed
            empty_stack(ptable->stack, 0);
        }

        cache_lock(c);
        release_pigeon_coop_hole(cp->free_page_tables, &(ptable->pch));
        cache_unlock(c);

        list_next(&sit, (skiplist_key_t **)&pseg, (skiplist_data_t **)&ptable);
    }

    cache_lock(c);
    log_printf(15, "BEFORE waitall seg=" XIDT " bytes_to_free=" XOT " bytes_used=" XOT " freed_bytes=" XOT " pending_bytes=" XOT "\n",
               segment_id(page_seg), bytes_to_free, cp->bytes_used, freed_bytes, pending_bytes);
    cache_unlock(c);


    //** Wait for any tasks to complete
    opque_waitall(q);
    opque_free(q, OP_DESTROY);

    //** Had this when we came in
    cache_lock(c);

    log_printf(15, "AFTER waitall seg=" XIDT " bytes_used=" XOT "\n", segment_id(page_seg), cp->bytes_used);

    cp->bytes_used -= freed_bytes;  //** Update how much I directly freed

    log_printf(15, "AFTER used update seg=" XIDT " bytes_used=" XOT "\n", segment_id(page_seg), cp->bytes_used);

    //** Clean up
    empty_skiplist(table);
    release_pigeon_coop_hole(cp->free_pending_tables, &pch);

    log_printf(15, "total_bytes marked for removal =" XOT "\n", total_bytes);

    return(total_bytes);
}
Example #3
0
int test_list()
{
	puts("starting tests");
	
	puts("##########################################");	
	puts("starting linked list tests");
	puts("##########################################");
	
	int value = 0;
	struct List *list = list_create();
	
	puts("empty list created");
	
	if (list_length(list) != 0) {
		printf("list_length of empty list should be zero\n");
		return 0;
	}

	puts("list_length ok");
	
	// Insert value 101 and test functions
	list_insert(list, 0, 101);
	if (list_length(list) != 1) {
		printf("list_length should be 1\n");
		return 0;
	}

	if (list_get(list, 0, &value) == 0) {
		printf("Error in list_get (1)\n");
		return 0;
	}
	if (value != 101) {
		printf("list_get should return value 101\n");
		return 0;
	}

	// Insert value 202 and test functions
	list_insert(list, 0, 202);
	if (list_length(list) != 2) {
		printf("list_length should return 2\n");
		return 0;
	}

	if (list_get(list, 0, &value) == 0) {
		printf("Error in list_length (2)\n");
		return 0;
	}
	if (value != 202) {
		printf("list_get should return 202\n");
		return 0;
	}

	puts("list_get ok");
	
	// Test remove function
	if (list_remove(list, 1) == 0) {
		printf("Error in list_remove\n");
		return 0;
	}
	if (list_length(list) != 1) {
		printf("list_length should return 1 (after remove)\n");
		return 0;
	}
	
	if (list_remove(list, 1) != 0) {
		printf("Error in list_remove\n");
		return 0;
	}
	if (list_length(list) != 1) {
		printf("list_length should return 1 (after remove)\n");
		return 0;
	}
	
	if (list_remove(list, 0) == 0) {
		printf("Error in list_remove\n");
		return 0;
	}
	
	if (list_length(list) != 0) {
		printf("list_length should return 0 (after remove)\n");
		return 0;
	}
	
	if (list_remove(list, 0) != 0) {
		printf("Error in list_remove\n");
		return 0;
	}
	
	if (list_length(list) != 0) {
		printf("list_length should return 0 (after remove)\n");
		return 0;
	}
	
	puts("list_remove ok");

	// Test pop function
	if (list_pop(list, &value) != 0) {
		printf("Error in list_pop\n");
		return 0;
	}
	
	list_append(list, 202);
	
	if (list_pop(list, &value) == 0) {
		printf("Error in list_pop\n");
		return 0;
	}

	if (value != 202) {
		printf("list_pop should return 202\n");
		return 0;
	}

	if (list_length(list) != 0) {
		printf("list_length should return 0 (after pop)\n");
		return 0;
	}

	puts("list_pop ok");

	// test list_append()
	
	list_append(list, -5);
	list_append(list, 0);
	list_append(list, 15);
	
	if (list_length(list) != 3) {
		printf("list_length should return 0 (after pop)\n");
		return 0;
	}
	
	if (list_get(list, 0, &value) != 1) {
		printf("Error in list_append\n");
		return 0;
	}
	
	if (value != -5) {
		printf("list_get should return -5\n");
		return 0;
	}
	
	if (list_get(list, 1, &value) != 1) {
		printf("Error in list_append\n");
		return 0;
	}
	
	if (value != 0) {
		printf("list_get should return 0\n");
		return 0;
	}

	if (list_get(list, 2, &value) != 1) {
		printf("Error in list_append\n");
		return 0;
	}
	
	if (value != 15) {
		printf("list_get should return 15\n");
		return 0;
	}
	
	if (list_pop(list, &value) == 0) {
		printf("Error in list_pop\n");
		return 0;
	}
	
	if (list_pop(list, &value) == 0) {
		printf("Error in list_pop\n");
		return 0;
	}
	
	if (list_pop(list, &value) == 0) {
		printf("Error in list_pop\n");
		return 0;
	}
	
	if (list_get(list, 0, &value) != 0) {
		printf("Error in list_get\n");
		return 0;
	}
	
	puts("list_append ok");
	
	// test list_prepend
	
	list_prepend(list, -5);
	list_prepend(list, 0);
	list_prepend(list, 15);
	
	if (list_length(list) != 3) {
		printf("list_length should return 0 (after pop)\n");
		return 0;
	}
	
	if (list_get(list, 0, &value) != 1) {
		printf("Error in list_append\n");
		return 0;
	}
	
	if (value != 15) {
		printf("list_get should return 15\n");
		return 0;
	}
	
	if (list_get(list, 1, &value) != 1) {
		printf("Error in list_append\n");
		return 0;
	}
	
	if (value != 0) {
		printf("list_get should return 0\n");
		return 0;
	}

	if (list_get(list, 2, &value) != 1) {
		printf("Error in list_append\n");
		return 0;
	}
	
	if (value != -5) {
		printf("list_get should return -5\n");
		return 0;
	}
	
	puts("list_prepend ok");
	
	// test list insert
	
	list_insert(list, -5, 0);
	
	if (list_length(list) != 4) {
		printf("list_length should return 4\n");
		return 0;
	}
	
	if (list_get(list, 0, &value) != 1) {
		printf("Error in list_append\n");
		return 0;
	}
	
	if (value != 0) {
		printf("list_get should return 0\n");
		return 0;
	}
	
	list_insert(list, 2, 100);

	if (list_length(list) != 5) {
		printf("list_length should return 5\n");
		return 0;
	}
	
	if (list_get(list, 2, &value) != 1) {
		printf("Error in list_append\n");
		return 0;
	}
	
	if (value != 100) {
		printf("list_get should return 100\n");
		return 0;
	}
	
	list_insert(list, 10, 500);
	
	if (list_length(list) != 6) {
		printf("list_length should return 6\n");
		return 0;
	}

	if (list_get(list, 5, &value) != 1) {
		printf("Error in list_append\n");
		return 0;
	}
	
	if (value != 500) {
		printf("list_get should return 500\n");
		return 0;
	}
	
	puts("list_insert ok");
	
	// test insert sorted
	
	for (int i = 0; i<6; i++)
		list_remove(list, 0);
	
	for (int i = 0; i<5; i++)
		list_append(list, i);
	
	list_append(list, 6);
	
	if (list_length(list) != 6) {
		printf("list_length should return 6\n");
		return 0;
	}
	
	list_insert_sorted(list, -1);
	list_insert_sorted(list, 5);
	list_insert_sorted(list, 7);
	
	for (int i = -1; i<8; i++)
	{
		list_get(list, i+1, &value);
		if (value != i)
			printf("error in list insert sorted\n");
	}
	
	// test print and  print reversed
	
	puts("list_insert_sorted ok");
	
	puts("print current list, should be sorted");
	
	list_print(list);
	
	puts("printing reversed list");
	
	list_print_reverse(list);
	
	puts("check print and print_reversed for yourself!");
	
	// test list remove all
	
	for (int i = 0; i<9; i++)
		list_remove(list, 0);
	
	for (int i = 0; i<5; i++)
		list_append(list, 5);
	
	list_remove_all(list, 5);
	
	if (list_length(list) != 0) {
		printf("list_length should return 0 (list remove all doesn't work\n");
		return 0;
	}
	
	for (int i = 0; i<9; i++)
		list_remove(list, 0);
	
	for (int i = 0; i<5; i++)
		list_append(list, 5);
	
	list_insert(list, -1, 0);
	list_remove_all(list, 5);
	
	if (list_length(list) != 1) {
		printf("list_length should return 1 (list remove all doesn't work\n");
		return 0;
	}
	
	for (int i = 0; i<9; i++)
		list_remove(list, 0);
	
	for (int i = 0; i<5; i++)
		list_append(list, 5);
	
	list_insert(list, 3, 0);
	list_remove_all(list, 5);
	
	if (list_length(list) != 1) {
		printf("list_length should return 1 (list remove all doesn't work\n");
		return 0;
	}
	
	for (int i = 0; i<9; i++)
		list_remove(list, 0);
	
	for (int i = 0; i<5; i++)
		list_append(list, 5);
	
	list_insert(list, 10, 0);
	list_remove_all(list, 5);
	
	if (list_length(list) != 1) {
		printf("list_length should return 1 (list remove all doesn't work\n");
		return 0;
	}
	
	puts("list_remove_all ok");

	puts("##########################################");	
	puts("all tests of linked lists completed");
	puts("##########################################");
	puts("------------------------------------------");
	
	list_delete(list);
	
	return 1;
}
Example #4
0
/* Inserts ELEM at the beginning of LIST, so that it becomes the
   front in LIST. */
void
list_push_front (struct list *list, struct list_elem *elem)
{
  list_insert (list_begin (list), elem);
}
Example #5
0
int main(int argc, char *argv[])
{
  int use_sorted = 0;

  if (argc < 3) {
    fprintf(stderr, "Usage: dict sort data_file.txt [lookup_commands.txt]\n"
        "sort: 0 or 1\n");
    return 1;
  }

  use_sorted = strtol(argv[1], NULL, 10);

  FILE *fp_data = fopen(argv[2], "rb");
  if (fp_data == NULL) {
    fprintf(stderr, "Error opening %s\n", argv[1]);
    return 1;
  }

  FILE *fp_cmd = NULL;
  if (argc > 3) {
    fp_cmd = fopen(argv[3], "rb");
    if (fp_cmd == NULL) {
      fprintf(stderr, "Error opening cmd file %s\n", argv[3]);
      return 1;
    }
  }

  struct list_data d;
  struct list_node *head = NULL;

  while (!feof(fp_data) && !ferror(fp_data)) {
    if (fscanf(fp_data, "%s %s", d.key, d.value) != 2)
      continue;

    if (use_sorted) {
      printf("Insert %s %s in sorted order\n", d.key, d.value);
      struct list_node *node_before = list_find_before(head, d.key);
      if (list_insert(&head, node_before, d) < 0) {
        fprintf(stderr, "Error while inserting into list: %s %s\n", d.key, d.value);
      }
    }
    else {
      printf("Insert %s %s in front\n", d.key, d.value);
      if (list_insert(&head, NULL, d) < 0) {
        fprintf(stderr, "Error while inserting into list: %s %s\n", d.key, d.value);
      }
    }

    list_print(head);
  }


  char lookup_key[MAX_KEY_LEN];
  struct list_node *lookup_node;

  while (fp_cmd && !feof(fp_cmd) && !ferror(fp_cmd)) {
    if (fscanf(fp_cmd, "%s", lookup_key) != 1)
      continue;

    if ((lookup_node = list_find_exact(head, lookup_key)) != NULL) {
      printf("Found: %s %s\n", lookup_node->data.key, lookup_node->data.value);
    }
    else {
      printf("Failed to find: %s\n", lookup_key);
    }
  }

  list_destroy(head);

  fclose(fp_data);

  if (fp_cmd) {
    fclose(fp_cmd);
  }

  return 0;
}
Example #6
0
int list_push(struct arr_list *arr, int obj) 
{
    return list_insert(arr, arr->index, obj);
}
Example #7
0
File: list.c Project: ASMlover/libc
int 
list_push_front(list_t L, element_t x)
{
  return list_insert(L, list_begin(L), x);
}
Example #8
0
/* =============================================================================
 * maze_read
 * -- Return number of path to route
 * =============================================================================
 */
long
maze_read (maze_t* mazePtr, char* inputFileName)
{
    FILE* inputFile = fopen(inputFileName, "rt");
    if (!inputFile) {
        fprintf(stderr, "Error: Could not read %s\n", inputFileName);
        exit(1);
    }

    /*
     * Parse input file
     */
    long lineNumber = 0;
    long height = -1;
    long width  = -1;
    long depth  = -1;
    char line[256];
    list_t* workListPtr = list_alloc(&coordinate_comparePair);
    vector_t* wallVectorPtr = mazePtr->wallVectorPtr;
    vector_t* srcVectorPtr = mazePtr->srcVectorPtr;
    vector_t* dstVectorPtr = mazePtr->dstVectorPtr;

    while (fgets(line, sizeof(line), inputFile)) {

        char code;
        long x1, y1, z1;
        long x2, y2, z2;
        long numToken = sscanf(line, " %c %li %li %li %li %li %li",
                              &code, &x1, &y1, &z1, &x2, &y2, &z2);

        lineNumber++;

        if (numToken < 1) {
            continue;
        }

        switch (code) {
            case '#': { /* comment */
                /* ignore line */
                break;
            }
            case 'd': { /* dimensions (format: d x y z) */
                if (numToken != 4) {
                    goto PARSE_ERROR;
                }
                width  = x1;
                height = y1;
                depth  = z1;
                if (width < 1 || height < 1 || depth < 1) {
                    goto PARSE_ERROR;
                }
                break;
            }
            case 'p': { /* paths (format: p x1 y1 z1 x2 y2 z2) */
                if (numToken != 7) {
                    goto PARSE_ERROR;
                }
                coordinate_t* srcPtr = coordinate_alloc(x1, y1, z1);
                coordinate_t* dstPtr = coordinate_alloc(x2, y2, z2);
                assert(srcPtr);
                assert(dstPtr);
                if (coordinate_isEqual(srcPtr, dstPtr)) {
                    goto PARSE_ERROR;
                }
                pair_t* coordinatePairPtr = pair_alloc(srcPtr, dstPtr);
                assert(coordinatePairPtr);
                bool_t status = list_insert(workListPtr, (void*)coordinatePairPtr);
                assert(status == TRUE);
                vector_pushBack(srcVectorPtr, (void*)srcPtr);
                vector_pushBack(dstVectorPtr, (void*)dstPtr);
                break;
            }
            case 'w': { /* walls (format: w x y z) */
                if (numToken != 4) {
                    goto PARSE_ERROR;
                }
                coordinate_t* wallPtr = coordinate_alloc(x1, y1, z1);
                vector_pushBack(wallVectorPtr, (void*)wallPtr);
                break;
            }
            PARSE_ERROR:
            default: { /* error */
                fprintf(stderr, "Error: line %li of %s invalid\n",
                        lineNumber, inputFileName);
                exit(1);
            }
        }

    } /* iterate over lines in input file */

    fclose(inputFile);

    /*
     * Initialize grid contents
     */
    if (width < 1 || height < 1 || depth < 1) {
        fprintf(stderr, "Error: Invalid dimensions (%li, %li, %li)\n",
                width, height, depth);
        exit(1);
    }
    grid_t* gridPtr = grid_alloc(width, height, depth);
    assert(gridPtr);
    mazePtr->gridPtr = gridPtr;
    addToGrid(gridPtr, wallVectorPtr, "wall");
    addToGrid(gridPtr, srcVectorPtr,  "source");
    addToGrid(gridPtr, dstVectorPtr,  "destination");
    printf("Maze dimensions = %li x %li x %li\n", width, height, depth);
    printf("Paths to route  = %li\n", list_getSize(workListPtr));

    /*
     * Initialize work queue
     */
    queue_t* workQueuePtr = mazePtr->workQueuePtr;
    list_iter_t it;
    list_iter_reset(&it, workListPtr);
    while (list_iter_hasNext(&it)) {
        pair_t* coordinatePairPtr = (pair_t*)list_iter_next(&it);
        queue_push(workQueuePtr, (void*)coordinatePairPtr);
    }
    list_free(workListPtr);

    return vector_getSize(srcVectorPtr);
}
//avec ces fils de premier seulement
void arbre_to_list_fils(list **lst,arbre *a)
{
    int i=a->size;
    i=a->size;
    while(i--)      list_insert(lst,a->fils[i]->node);
}
/*
 * Free DevCB
 */
static void delDevCB( DevCB *devcb )
{
	list_delete(&devcb->q);
	list_insert(&devcb->q, &FreeDevCB);
	devcb->devnm[0] = '\0';
}
/**
 * ListIterator list_iterator_create (List l);
 * void * list_next (ListIterator i);
 * void list_iterator_reset (ListIterator i);
 * void *list_insert (ListIterator i, void *x);
 * void * list_find (ListIterator i, ListFindF f, void *key);
 * void list_iterator_destroy (ListIterator i)
 * void * list_remove (ListIterator i);
 * int list_delete_item (ListIterator i);
 */
void it_test_1()
{
	ListIterator it = NULL;
	stu_t *node = NULL;
	long key = 90005L;
	void *pos = NULL;
	int count = 0;

	/* create iterator! */
	it = list_iterator_create (stu_list);
	/* list_next until NULL */
	while ( NULL != (node = (stu_t*)list_next(it)) ) {
		printf("id = %ld, name = %s, age = %f\n", node->id, node->name, node->age);
	}

	/********** insert ******************/
	/* reset it to the start of list */
	list_iterator_reset(it);
	while ( NULL != (node = (stu_t*)list_next(it)) ) {
		if (5 == node->age){
			node = xmalloc(sizeof(stu_t));
			node->id = 999999L;
			node->age = 5.5;
			node->name = xstrdup("name_5.5");
			/* list_insert: insert a new node */
			list_insert (it, node);
			break;
		}
	}

	/*******  traverse: the list via list_next(it) **********/
	/* reset it to the start of list */
	list_iterator_reset(it);
	/* after insert, list_next until NULL */
	puts("=========after insert:");
	while ( NULL != (node = (stu_t*)list_next(it)) ) {
		printf("id = %ld, name = %s, age = %f\n", node->id, node->name, node->age);
	}

	/************   find    ******************/
	/* reset it to the start of list */
	list_iterator_reset(it);
	/* list_find: traverse the list using *it*, to find the node with the '*key' */
	if (NULL != (pos = list_find(it, list_find_stu_id_f, &key))) {
		printf("found! id = %ld, name = %s, age = %f\n", ((stu_t *)pos)->id, ((stu_t *)pos)->name, ((stu_t *)pos)->age);
	} else {
		puts("not found");
	}

	/************   remove    ******************/
	/* remove the node to which 'it' currently points, does not free the node */
	pos = list_remove (it);
	printf("removed! id = %ld, name = %s, age = %f\n", ((stu_t *)pos)->id, ((stu_t *)pos)->name, ((stu_t *)pos)->age);
	/* Note: free the removed node */
	xfree(((stu_t *)pos)->name);
	xfree(pos);

	/* reset it to the start of list */
	list_iterator_reset(it);
	/* after remove, list_next until NULL */
	puts("=========after remove, list is:");
	while ( NULL != (node = (stu_t*)list_next(it)) ) {
		printf("id = %ld, name = %s, age = %f\n", node->id, node->name, node->age);
	}


	/************   find  and delete   ******************/
	/* reset it to the start of list */
	list_iterator_reset(it);
	/* list_find: traverse the list using *it*, to find the node with the '*key' */
	key = 999999L;
	if (NULL != (pos = list_find(it, list_find_stu_id_f, &key))) {
		printf("found! id = %ld, name = %s, age = %f\n", ((stu_t *)pos)->id, ((stu_t *)pos)->name, ((stu_t *)pos)->age);
	} else {
		puts("not found");
	}

	/* delete item, automatically free the item's memory via
	 * the default delete func specified when
	 * list_create(_list_delete_node_f)
	 */
	count = list_delete_item (it);
	if (count == 1)
		puts("deleting successful");
	else
		puts("deleting failed");
	/* reset it to the start of list */
	list_iterator_reset(it);
	/* after deleting, list_next until NULL */
	puts("=========after deleting, list is:");
	while ( NULL != (node = (stu_t*)list_next(it)) ) {
		printf("id = %ld, name = %s, age = %f\n", node->id, node->name, node->age);
	}

	/* Note: remember to destroy iterator */
	list_iterator_destroy(it);
}
Example #12
0
/*
 * generate anonymized strings preserving lexicographic-order
 *
 * only strings between start and end (including start, excluding end)
 * will be processed
 * set end to null to process list to the end
 * prev_length - length of prefixes already processed. Hence all
 * strings in the range must be longer or of equal
 * length. Furthermore, all strings in the range are expected to have
 * identical prefixes of prev_length.
 * aprefix - anonymized prefix (first prev_length chars)
 */
static int
generate_lex_anonymizations(anon_octs_t *a, size_t prev_length,
                            const char* aprefix,
                            struct node *start, struct node *end)
{
    char* str;  /* prefix up to min_length */
    char* astr; /* astr - anonymized str */
    char* prefix; /* prefix of prev_length - same for all strings in group */
    //char* aprefix; /* anonymized (hash of) prefix */
    //char* middle; /* part of string between prev_length and min_length */
    char* amiddle; /* anonymized (hash of) middle */
    struct node *p, *q; /* nodes in list */
    struct node *start2; /* recursively process this part of the list */
    size_t min_length; /* minimum string length in our part of list */
    int count; /* number of unique prefixes (of min_length) */
    struct node* hashlist = NULL; /* stores generated amiddle's */
    struct node *hp; /* nodes in hash list */
    struct hash_node* node = NULL; /* lhash table node */
    int i;

    assert(a);
    if (!start)
        return 0;
    assert(aprefix || prev_length > 0);

    /* find min length */
    min_length = strlen(start->data);
    for (p = start; p && p!=end; p = p->next) {
        int tmp = strlen(p->data);
        if (tmp < min_length) {
            min_length = tmp;
        }
    }
    assert(min_length > prev_length);

    /* count unique prefixes of min_length (after position prev_length) */
    count = 0;
    for (p = start, q = NULL; p && p!=end; q = p, p = p->next) {
        if (q) {
            if (strncmp(p->data+prev_length, q->data+prev_length,
                        min_length-prev_length)) {
                count++;
            }
        } else { /* first element in list */
            count++;
        }
    }

    /*  produce hashlist (amiddle) */
    for (i=0; i<count; i++) {
        do {
            amiddle = (char*) malloc(min_length-prev_length+1);
            amiddle = generate_random_string(amiddle, min_length-prev_length);
        } while (list_insert(&hashlist,amiddle)==1);
    }

    /* assign anon. strings to real strings and store them in lhash table */
    str = (char*) malloc(min_length+1);
    astr = (char*) malloc(min_length+1);
    assert(str);
    assert(astr);
    hp = hashlist;
    int group_size = 0; /* size of last group
			 * excluding min_lenght element (if it exists)
			 */
    int is_diff = 0; /* is current string (p) different from previous one (q)
		      * up to min_length?
		      */
    int was_minlength = 0; /* if last group contained (==started with)
			    * a string of min_length
			    * - determines if we need to allocate new str, astr
			    */
    start2 = start;
    for (p = start, q = NULL; p && p!=end; q = p, p = p->next) {
        /*
        fprintf(stderr, "assigning %s (hp: %s)...\n",
        	p->data, (hp)?hp->data:"NULL");
        */
        assert(strlen(p->data) >= min_length);
        /* check if p is different from q up to first min_length chars */
        is_diff = 0;
        if (q) {
            if (strncmp(p->data+prev_length, q->data+prev_length,
                        min_length-prev_length)) {
                is_diff = 1;
            } else {
                group_size++;
            }
        } else {
            /* first item in list */
            is_diff = 1;
        }
        if (is_diff) {
            if (q) { /* don't call for first item in list */
                /* anonymize the previous group */
                if (group_size > 0) {
                    assert(strlen(start2->data) > min_length);
                    generate_lex_anonymizations(a, min_length, astr,
                                                start2, p);
                }
                if (was_minlength) {
                    str = (char*) malloc(min_length+1);
                    astr = (char*) malloc(min_length+1);
                    assert(str);
                    assert(astr);
                }
            }
            start2 = p;
            /* prepare str, astr */
            strncpy(str, p->data, min_length);
            str[min_length] = '\0';
            /* aprefix generated earlier and passed as a function argument */
            strncpy(astr, aprefix, prev_length);
            assert(hp);
            assert(hp->data);
            strncpy(astr+prev_length, hp->data, min_length-prev_length);
            astr[min_length] = '\0';

            if (strlen(p->data) == min_length) {
                /* store (str, astr) in lhash */
                node = (struct hash_node*) malloc(sizeof(struct hash_node));
                assert(node);
                node->data = str;
                node->hash = astr;
                /*
                fprintf(stderr, "storing in hash table [%s --> %s]\n",
                	str, astr);
                */
                lh_insert(a->hash_table, node);
                /* omit this (min_length) element from recursion */
                start2 = p->next;
                was_minlength = 1;
                group_size = 0;
            } else {
                /* don't need to store (str, astr) in lhash */
                was_minlength = 0;
                group_size = 1;
            }
            /* advance to next node in hashlist */
            hp = hp->next;

        } /* else do nothing */
    }
    if (start2 && group_size > 0) {
        assert(strlen(start2->data) > min_length);
        generate_lex_anonymizations(a, min_length, astr, start2, end);
    }
    if (was_minlength) {
        str = (char*) malloc(min_length+1);
        astr = (char*) malloc(min_length+1);
        assert(str);
        assert(astr);
    }

    /* we don't need the list of used strings anymore */
    //list_remove_all(&(a->list));
    list_remove_all(&hashlist);
    free(str);
    free(astr);
    return 0;
}
Example #13
0
int list_add(list* ls, void* element)
{
	return list_insert(ls, element, ls->count);
}
Example #14
0
void runserver(int numthreads, unsigned short serverport) {
    //////////////////////////////////////////////////

	linkedlist* socks = malloc(sizeof(linkedlist));
	socks-> head = malloc(sizeof(struct node));
	(socks->head)->socket = -1;
	socks->tail = socks->head;
	socks->listlock = malloc(sizeof(pthread_mutex_t));
	pthread_mutex_init(socks->listlock, NULL);
	socks->listempty = malloc(sizeof(pthread_cond_t));
	pthread_cond_init(socks->listempty,NULL);
    // create your pool of threads here
	if(numthreads<1){
		numthreads = 1;
	}
	pthread_t** threads = malloc(sizeof(pthread_t*)*numthreads);
	int i = 0;
	for(; i < numthreads; i++){
		threads[i] = malloc(sizeof(pthread_t));
		pthread_create(threads[i], NULL, sock_consume, (void*)socks);
	}

    //////////////////////////////////////////////////
    
    
    int main_socket = prepare_server_socket(serverport);
    if (main_socket < 0) {
        exit(-1);
    }
    signal(SIGINT, signal_handler);

    struct sockaddr_in client_address;
    socklen_t addr_len;

    fprintf(stderr, "Server listening on port %d.  Going into request loop.\n", serverport);
    while (still_running) {
        struct pollfd pfd = {main_socket, POLLIN};
        int prv = poll(&pfd, 1, 10000);

        if (prv == 0) {
            continue;
        } else if (prv < 0) {
            PRINT_ERROR("poll");
            still_running = FALSE;
            continue;
        }
        
        addr_len = sizeof(client_address);
        memset(&client_address, 0, addr_len);

        int new_sock = accept(main_socket, (struct sockaddr *)&client_address, &addr_len);
        if (new_sock > 0) {
            
            fprintf(stderr, "Got connection from %s:%d\n", inet_ntoa(client_address.sin_addr), ntohs(client_address.sin_port));

           ////////////////////////////////////////////////////////
           /* You got a new connection.  Hand the connection off
            * to one of the threads in the pool to process the
            * request.
            *
            * Don't forget to close the socket (in the worker thread)
            * when you're done.
            */
           ////////////////////////////////////////////////////////

			pthread_mutex_lock(socks-> listlock);
			list_insert(new_sock, &socks->tail);
			(socks->tail)-> ip = strdup(inet_ntoa(client_address.sin_addr)); //malloc! The free is taken care of in list_remove.
			(socks->tail)-> port = ntohs(client_address.sin_port);
			pthread_cond_broadcast(socks->listempty);
			pthread_mutex_unlock(socks->listlock);

        }
    }

	i = 0;
	for(; i < numthreads; i++){
		pthread_join(*(threads[i]), NULL);
		free(threads[i]);	
	}
	free(threads);
	
	free(socks->listlock);
	free(socks->listempty);
	free(socks);
	
    fprintf(stderr, "Server shutting down.\n");
        
    close(main_socket);
}
Example #15
0
static void 
read_path(FILE *fob, mxArray **data, double dbu_to_uu) 
{
   mxArray *pstruct;
   mxArray *pprop = NULL;
   mxArray *pc;
   tList xylist;
   uint16_t rtype, rlen;
   int nprop = 0;
   int nle, k;
   element_t path;
   const char *fields[] = {"internal", "xy", "prop"};


   /* initialize element */
   init_element(&path, GDS_PATH);

   /* output data structure */
   pstruct = mxCreateStructMatrix(1,1, 3, fields);

   /* create a list for the XY data record(s) */
   if ( create_list(&xylist) == -1 )
      mexErrMsgTxt("gds_read_element (path) :  could not create list for XY records.");

   /* read element properties */
   while (1) {
      
      if ( read_record_hdr(fob, &rtype, &rlen) )
	 mexErrMsgTxt("gds_read_element (path) :  could not read record header.");

      if (rtype == ENDEL)
	 break;

      switch (rtype) {

         case XY:
	    if ( list_insert(xylist, read_xy(fob, rlen, dbu_to_uu), AFTER) == -1)
	       mexErrMsgTxt("gds_read_element (path) :  list insertion failed.");
	    break;

         case LAYER:
	    path.layer = read_layer(fob);
	    break;

         case PATHTYPE:
	    path.ptype = read_type(fob);
	    path.has |= HAS_PTYPE;
	    break;

         case WIDTH:
	    path.width = dbu_to_uu * (double)read_width(fob);
	    path.has |= HAS_WIDTH;
	    break;

         case BGNEXTN:
	    path.bgnextn = dbu_to_uu * read_extn(fob);
	    path.has |= HAS_BGNEXTN;
	    break;

         case ENDEXTN:
	    path.endextn = dbu_to_uu * read_extn(fob);
	    path.has |= HAS_ENDEXTN;
	    break;

         case DATATYPE:
	    path.dtype = read_type(fob);
	    break;

         case ELFLAGS:
	    path.elflags = read_elflags(fob);
	    path.has |= HAS_ELFLAGS;
	    break;

         case PLEX:
	    path.plex = read_plex(fob);
	    path.has |= HAS_PLEX;
	    break;

         case PROPATTR:
	    pprop = resize_property_structure(pprop, nprop+1);
	    mxSetFieldByNumber(pprop, nprop, 0, read_propattr(fob));
	    break;

         case PROPVALUE:
 	    mxSetFieldByNumber(pprop, nprop, 1, read_propvalue(fob,rlen));
	    nprop += 1;
	    break;

         default:
	    mexPrintf("Unknown record id: 0x%x\n", rtype);
	    mexErrMsgTxt("PATH :  found unknown element property.");
      }
   }

   /* cell array with XY records */
   nle = list_entries(xylist);
   if ( !nle )
      mexErrMsgTxt("gds_read_element (path) :  element has no XY record.");
   pc = mxCreateCellMatrix(1, nle);
   list_head(xylist);
   for (k=0; k<nle; k++)
      mxSetCell(pc, k, (mxArray *)get_current_entry(xylist, NULL));
   mxSetFieldByNumber(pstruct, 0, 1, pc);

   /* set prop field */
   if ( nprop ) {
      mxSetFieldByNumber(pstruct, 0, 2, pprop);
   }
   else {
      mxSetFieldByNumber(pstruct, 0, 2, empty_matrix());
   }

   /* store structure with element data */
   mxSetFieldByNumber(pstruct, 0, 0, copy_element_to_array(&path));

   /* return data */
   *data = pstruct;
}
Example #16
0
/*
 * list_insert_tail
 *
 * Insert an element into the tail of the list
 */
int
list_insert_tail (list_t *list, list_elem_t *elem)
{
    /* Just call list_insert */
    return (list_insert(list, elem));
}
Example #17
0
File: omgidl.c Project: spchamp/ilu
int main(int argc, char* argv[])
{
  char *filename;
  extern FILE* idlin;
  extern int idl_flex_debug;
  list defs;
  list toplevel_prefix; /* Current prefix for repository ID. */
  int i;

  search_list = iluparser_new_list ();

  for (i = 1; i < argc; i++){
    if (argv[i][0] != '-')
      break;
    switch (argv[i][1]){
    case 'a':
      idl_subset |= IDL_STYLE_GUIDE;
      break;
    case 'I':
      if (argv[i][2])
	list_insert (search_list, argv[i]+2);
      else
	list_insert (search_list, argv[++i]);
      break;
    case 'h':
    default:
      usage();
      break;
    }
  }
  if (i+1 != argc)
    usage();
  filename = argv[i];
	
  /* Open top-level IDL file. */
  init_types();
  idl_flex_debug=0;
  if ((idlin = fopen (filename, "r")) == NULL)
    {
      perror(argv[1]);
      exit(1);
    }

  /* Syntactical analysis */
  idlsetinitialfile(filename);
  if(idlparse())
    return 1;
  defs = the_result;

  /* Semantical analysis */

  /* join modules for re-opening */
  defs = reopen_modules (defs);
  /* backlink, toplevel has no parent */
  list_enumerate (defs, definition_backlink,0);
  /* resolve all names */
  list_enumerate (defs, definition_resolvenames, defs);
  /* perform consistency checks, compute constants */
  list_enumerate (defs, definition_check, defs);
  /* assign repository IDs */
  toplevel_prefix = iluparser_new_list ();
  list_push (toplevel_prefix, "");
  list_enumerate (defs, definition_setuid, toplevel_prefix);
  /* Test conformance with AB style guide */
  list_enumerate (defs, ab_style, 0);

  /* Drop all results :-) */
  return 0;
}
Example #18
0
/**
 * Inserts an element into the mount_info linked list.
 *
 * @param entry element to insert into the list
 */
void mount_info_list_insert(struct mount_info *entry) {
    list_insert((void **)&mount_info_list_head, (void *)entry, mount_info_next, mount_info_set_next);
}
Example #19
0
File: list.c Project: ASMlover/libc
int 
list_push_back(list_t L, element_t x)
{
  return list_insert(L, list_end(L), x);
}
Example #20
0
/**
 * Inserts an element into the fd_entry linked list.
 *
 * @param entry element to insert into the list
 */
void fd_entry_list_insert(struct fd_entry *entry) {
    list_insert((void **)&fd_list_head, (void *)entry, fd_entry_next, fd_entry_set_next);
}
Example #21
0
void selector_prepend(caValue* selector, caValue* element)
{
    copy(element, list_insert(selector, 0));
}
Example #22
0
File: list.c Project: milolx/ipcf
/* Inserts 'elem' at the beginning of 'list', so that it becomes the front in
   'list'. */
void
list_push_front(struct list *list, struct list *elem)
{
    list_insert(list->next, elem);
}
Example #23
0
/* Inserts ELEM at the end of LIST, so that it becomes the
   back in LIST. */
void
list_push_back (struct list *list, struct list_elem *elem)
{
  list_insert (list_end (list), elem);
}
Example #24
0
File: list.c Project: milolx/ipcf
/* Inserts 'elem' at the end of 'list', so that it becomes the back in
 * 'list'. */
void
list_push_back(struct list *list, struct list *elem)
{
    list_insert(list, elem);
}
Example #25
0
int service_pop3_init(char *ip, int sp, unsigned char options, char *miscptr, FILE * fp, int port) {
  int myport = PORT_POP3, mysslport = PORT_POP3_SSL;
  char *ptr = NULL;
  int sock = -1;
  char *capa_str = "CAPA\r\n";
  char *quit_str = "QUIT\r\n";
  pool p;

  p.pop3_auth_mechanism = AUTH_CLEAR;
  p.disable_tls = 1;
  memcpy(p.ip, ip, 36);

  if (sock >= 0)
    sock = hydra_disconnect(sock);
//      sleepn(300);
  if ((options & OPTION_SSL) == 0) {
    if (port != 0)
      myport = port;
    sock = hydra_connect_tcp(p.ip, myport);
  } else {
    if (port != 0)
      mysslport = port;
    sock = hydra_connect_ssl(p.ip, mysslport);
  }
  if (sock < 0) {
    if (verbose || debug)
      hydra_report(stderr, "[ERROR] pid %d terminating, can not connect\n", (int) getpid());
    return -1;
  }
  buf = hydra_receive_line(sock);
  if (buf == NULL || buf[0] != '+') {   /* check the first line */
    if (verbose || debug)
      hydra_report(stderr, "[ERROR] Not an POP3 protocol or service shutdown: %s\n", buf);
    return -1;
  }

  ptr = strstr(buf, "<");
  if (ptr != NULL && buf[0] == '+') {
    if (ptr[strlen(ptr) - 1] == '\n')
      ptr[strlen(ptr) - 1] = 0;
    if (ptr[strlen(ptr) - 1] == '\r')
      ptr[strlen(ptr) - 1] = 0;
    strcpy(apop_challenge, ptr);
  }
  free(buf);

  /* send capability request */
  if (hydra_send(sock, capa_str, strlen(capa_str), 0) < 0) {
    if (verbose || debug)
      hydra_report(stderr, "[ERROR] Can not send the CAPABILITY request\n");
    return -1;
  }

  buf = pop3_read_server_capacity(sock);

  if (buf == NULL) {
    hydra_report(stderr, "[ERROR] No answer from CAPABILITY request\n");
    return -1;
  }

  if ((miscptr != NULL) && (strlen(miscptr) > 0)) {
    int i;

    for (i = 0; i < strlen(miscptr); i++)
      miscptr[i] = (char) toupper((int) miscptr[i]);

    if (strstr(miscptr, "TLS") || strstr(miscptr, "SSL")) {
      p.disable_tls = 0;
    }
  }

#ifdef LIBOPENSSL
  if (!p.disable_tls) {
    /* check for STARTTLS, if available we may have access to more basic auth methods */
    if (strstr(buf, "STLS") != NULL) {
      hydra_send(sock, "STLS\r\n", strlen("STLS\r\n"), 0);
      free(buf);
      buf = hydra_receive_line(sock);
      if (buf[0] != '+') {
        hydra_report(stderr, "[ERROR] TLS negotiation failed, no answer received from STARTTLS request\n");
      } else {
        free(buf);
        if ((hydra_connect_to_ssl(sock) == -1)) {
          if (verbose)
            hydra_report(stderr, "[ERROR] Can't use TLS\n");
          p.disable_tls = 1;
        } else {
          if (verbose)
            hydra_report(stderr, "[VERBOSE] TLS connection done\n");
        }
        if (!p.disable_tls) {
          /* ask again capability request but in TLS mode */
          if (hydra_send(sock, capa_str, strlen(capa_str), 0) < 0) {
            if (verbose || debug)
              hydra_report(stderr, "[ERROR] Can not send the CAPABILITY request\n");
            return -1;
          }
          buf = pop3_read_server_capacity(sock);
          if (buf == NULL) {
            hydra_report(stderr, "[ERROR] No answer from CAPABILITY request\n");
            return -1;
          }
        }
      }
    } else
      hydra_report(stderr, "[ERROR] option to use TLS/SSL failed as it is not supported by the server\n");
  }
#endif

  if (hydra_send(sock, quit_str, strlen(quit_str), 0) < 0) {
    //we dont care if the server is not receiving the quit msg
  }
  hydra_disconnect(sock);


  if (verbose)
    hydra_report(stderr, "[VERBOSE] CAPABILITY: %s", buf);

  /* example:
     +OK Capability list follows:
     TOP
     LOGIN-DELAY 180
     UIDL
     USER
     SASL PLAIN LOGIN
   */

  /* according to rfc 2449:
     The POP3 AUTH command [POP-AUTH] permits the use of [SASL]
     authentication mechanisms with POP3.  The SASL capability
     indicates that the AUTH command is available and that it supports
     an optional base64 encoded second argument for an initial client
     response as described in the SASL specification.  The argument to
     the SASL capability is a space separated list of SASL mechanisms
     which are supported.
   */

  /* which mean threre will *always* have a space before the LOGIN auth keyword */
  if ((strstr(buf, " LOGIN") == NULL) && (strstr(buf, "NTLM") != NULL)) {
    p.pop3_auth_mechanism = AUTH_NTLM;
  }
#ifdef LIBOPENSSL
  if ((strstr(buf, " LOGIN") == NULL) && (strstr(buf, "DIGEST-MD5") != NULL)) {
    p.pop3_auth_mechanism = AUTH_DIGESTMD5;
  }

  if ((strstr(buf, " LOGIN") == NULL) && (strstr(buf, "CRAM-SHA256") != NULL)) {
    p.pop3_auth_mechanism = AUTH_CRAMSHA256;
  }

  if ((strstr(buf, " LOGIN") == NULL) && (strstr(buf, "CRAM-SHA1") != NULL)) {
    p.pop3_auth_mechanism = AUTH_CRAMSHA1;
  }

  if ((strstr(buf, " LOGIN") == NULL) && (strstr(buf, "CRAM-MD5") != NULL)) {
    p.pop3_auth_mechanism = AUTH_CRAMMD5;
  }
#endif

  if ((strstr(buf, " LOGIN") == NULL) && (strstr(buf, "PLAIN") != NULL)) {
    p.pop3_auth_mechanism = AUTH_PLAIN;
  }

  if (strstr(buf, " LOGIN") != NULL) {
    p.pop3_auth_mechanism = AUTH_LOGIN;
  }

  if (strstr(buf, "SASL") == NULL) {
#ifdef LIBOPENSSL
    if (strlen(apop_challenge) == 0) {
      p.pop3_auth_mechanism = AUTH_CLEAR;
    } else {
      p.pop3_auth_mechanism = AUTH_APOP;
    }
#else
    p.pop3_auth_mechanism = AUTH_CLEAR;
#endif

  }
  free(buf);

  if ((miscptr != NULL) && (strlen(miscptr) > 0)) {

    if (strstr(miscptr, "CLEAR"))
      p.pop3_auth_mechanism = AUTH_CLEAR;

    if (strstr(miscptr, "LOGIN"))
      p.pop3_auth_mechanism = AUTH_LOGIN;

    if (strstr(miscptr, "PLAIN"))
      p.pop3_auth_mechanism = AUTH_PLAIN;

#ifdef LIBOPENSSL
    if (strstr(miscptr, "APOP"))
      p.pop3_auth_mechanism = AUTH_APOP;

    if (strstr(miscptr, "CRAM-MD5"))
      p.pop3_auth_mechanism = AUTH_CRAMMD5;

    if (strstr(miscptr, "CRAM-SHA1"))
      p.pop3_auth_mechanism = AUTH_CRAMSHA1;

    if (strstr(miscptr, "CRAM-SHA256"))
      p.pop3_auth_mechanism = AUTH_CRAMSHA256;

    if (strstr(miscptr, "DIGEST-MD5"))
      p.pop3_auth_mechanism = AUTH_DIGESTMD5;
#endif

    if (strstr(miscptr, "NTLM"))
      p.pop3_auth_mechanism = AUTH_NTLM;

  }

  if (verbose) {
    switch (p.pop3_auth_mechanism) {
    case AUTH_CLEAR:
      hydra_report(stderr, "[VERBOSE] using POP3 CLEAR LOGIN mechanism\n");
      break;
    case AUTH_LOGIN:
      hydra_report(stderr, "[VERBOSE] using POP3 LOGIN AUTH mechanism\n");
      break;
    case AUTH_PLAIN:
      hydra_report(stderr, "[VERBOSE] using POP3 PLAIN AUTH mechanism\n");
      break;
    case AUTH_APOP:
#ifdef LIBOPENSSL
      if (strlen(apop_challenge) == 0) {
        hydra_report(stderr, "[VERBOSE] APOP not supported by server, using clear login\n");
        p.pop3_auth_mechanism = AUTH_CLEAR;
      } else {
        hydra_report(stderr, "[VERBOSE] using POP3 APOP AUTH mechanism\n");
      }
#else
      p.pop3_auth_mechanism = AUTH_CLEAR;
#endif
      break;
#ifdef LIBOPENSSL
    case AUTH_CRAMMD5:
      hydra_report(stderr, "[VERBOSE] using POP3 CRAM-MD5 AUTH mechanism\n");
      break;
    case AUTH_CRAMSHA1:
      hydra_report(stderr, "[VERBOSE] using POP3 CRAM-SHA1 AUTH mechanism\n");
      break;
    case AUTH_CRAMSHA256:
      hydra_report(stderr, "[VERBOSE] using POP3 CRAM-SHA256 AUTH mechanism\n");
      break;
    case AUTH_DIGESTMD5:
      hydra_report(stderr, "[VERBOSE] using POP3 DIGEST-MD5 AUTH mechanism\n");
      break;
#endif
    case AUTH_NTLM:
      hydra_report(stderr, "[VERBOSE] using POP3 NTLM AUTH mechanism\n");
      break;

    }
  }

  if (!plist)
    plist = list_create(p);
  else
    plist = list_insert(p);

  return 0;
}
Example #26
0
/**
 * canonicalize_path: Canonicalize a path.
 *
 * @param cwd   Current working directory
 * @param input Path to append or canonicalize on
 * @returns An absolute path string
 */
char *canonicalize_path(char *cwd, char *input) {
	/* This is a stack-based canonicalizer; we use a list as a stack */
	list_t *out = list_create();

	/*
	 * If we have a relative path, we need to canonicalize
	 * the working directory and insert it into the stack.
	 */
	if (strlen(input) && input[0] != PATH_SEPARATOR) {
		/* Make a copy of the working directory */
		char *path = malloc((strlen(cwd) + 1) * sizeof(char));
		memcpy(path, cwd, strlen(cwd) + 1);

		/* Setup tokenizer */
		char *pch;
		char *save;
		pch = strtok_r(path,PATH_SEPARATOR_STRING,&save);

		/* Start tokenizing */
		while (pch != NULL) {
			/* Make copies of the path elements */
			char *s = malloc(sizeof(char) * (strlen(pch) + 1));
			memcpy(s, pch, strlen(pch) + 1);
			/* And push them */
			list_insert(out, s);
			pch = strtok_r(NULL,PATH_SEPARATOR_STRING,&save);
		}
		free(path);
	}

	/* Similarly, we need to push the elements from the new path */
	char *path = malloc((strlen(input) + 1) * sizeof(char));
	memcpy(path, input, strlen(input) + 1);

	/* Initialize the tokenizer... */
	char *pch;
	char *save;
	pch = strtok_r(path,PATH_SEPARATOR_STRING,&save);

	/*
	 * Tokenize the path, this time, taking care to properly
	 * handle .. and . to represent up (stack pop) and current
	 * (do nothing)
	 */
	while (pch != NULL) {
		if (!strcmp(pch,PATH_UP)) {
			/*
			 * Path = ..
			 * Pop the stack to move up a directory
			 */
			node_t * n = list_pop(out);
			if (n) {
				free(n->value);
				free(n);
			}
		} else if (!strcmp(pch,PATH_DOT)) {
			/*
			 * Path = .
			 * Do nothing
			 */
		} else {
			/*
			 * Regular path, push it
			 * XXX: Path elements should be checked for existence!
			 */
			char * s = malloc(sizeof(char) * (strlen(pch) + 1));
			memcpy(s, pch, strlen(pch) + 1);
			list_insert(out, s);
		}
		pch = strtok_r(NULL, PATH_SEPARATOR_STRING, &save);
	}
	free(path);

	/* Calculate the size of the path string */
	size_t size = 0;
	foreach(item, out) {
		/* Helpful use of our foreach macro. */
		size += strlen(item->value) + 1;
	}
Example #27
0
static int
SubstituteFile(
    const char *substitutions,
    const char *filename)
{
    size_t cbBuffer = 1024;
    static char szBuffer[1024], szCopy[1024];
    char *szResult = NULL;
    list_item_t *substPtr = NULL;
    FILE *fp, *sp;

    fp = fopen(filename, "rt");
    if (fp != NULL) {

	/*
	 * Build a list of substutitions from the first filename
	 */

	sp = fopen(substitutions, "rt");
	if (sp != NULL) {
	    while (fgets(szBuffer, cbBuffer, sp) != NULL) {
		char *ks, *ke, *vs, *ve;
		ks = szBuffer;
		while (ks && *ks && isspace(*ks)) ++ks;
		ke = ks;
		while (ke && *ke && !isspace(*ke)) ++ke;
		vs = ke;
		while (vs && *vs && isspace(*vs)) ++vs;
		ve = vs;
		while (ve && *ve && !(*ve == '\r' || *ve == '\n')) ++ve;
		*ke = 0, *ve = 0;
		list_insert(&substPtr, ks, vs);
	    }
	    fclose(sp);
	}

	/* debug: dump the list */
#ifdef _DEBUG
	{
	    int n = 0;
	    list_item_t *p = NULL;
	    for (p = substPtr; p != NULL; p = p->nextPtr, ++n) {
		fprintf(stderr, "% 3d '%s' => '%s'\n", n, p->key, p->value);
	    }
	}
#endif

	/*
	 * Run the substitutions over each line of the input
	 */

	while (fgets(szBuffer, cbBuffer, fp) != NULL) {
	    list_item_t *p = NULL;
	    for (p = substPtr; p != NULL; p = p->nextPtr) {
		char *m = strstr(szBuffer, p->key);
		if (m != NULL) {
		    char *cp, *op, *sp;
		    cp = szCopy;
		    op = szBuffer;
		    while (op != m) *cp++ = *op++;
		    sp = p->value;
		    while (sp && *sp) *cp++ = *sp++;
		    op += strlen(p->key);
		    while (*op) *cp++ = *op++;
		    *cp = 0;
		    memcpy(szBuffer, szCopy, sizeof(szCopy));
		}
	    }
	    printf(szBuffer);
	}

	list_free(&substPtr);
    }
    fclose(fp);
    return 0;
}
Example #28
0
int main (int argc, char * argv[]) {

    /* Parse arguments */
    char * p = ".";

    if (argc > 1) {
        int index, c;
        while ((c = getopt(argc, argv, "ahl?")) != -1) {
            switch (c) {
            case 'a':
                show_hidden = 1;
                break;
            case 'h':
                human_readable = 1;
                break;
            case 'l':
                long_mode = 1;
                break;
            case '?':
                show_usage(argc, argv);
                return 0;
            }
        }

        if (optind < argc) {
            p = argv[optind];
        }
        if (optind + 1 < argc) {
            print_dir = 1;
        }
    }

    stdout_is_tty = isatty(STDOUT_FILENO);

    if (long_mode) {
        struct tm * timeinfo;
        struct timeval now;
        gettimeofday(&now, NULL); //time(NULL);
        timeinfo = localtime((time_t *)&now.tv_sec);
        this_year = timeinfo->tm_year;
    }

    if (stdout_is_tty) {
        struct winsize w;
        ioctl(1, TIOCGWINSZ, &w);
        term_width = w.ws_col;
        term_height = w.ws_row;
        term_width -= 1; /* And this just helps clean up our math */
    }

    int out = 0;

    if (argc == 1 || optind == argc) {
        display_dir(p);
    } else {
        list_t * files = list_create();
        while (p) {
            struct tfile * f = malloc(sizeof(struct tfile));

            f->name = p;
            int t = stat(p, &f->statbuf);

            if (t < 0) {
                printf("ls: cannot access %s: No such file or directory\n", p);
                free(f);
                out = 2;
            }

            list_insert(files, f);

            optind++;
            if (optind >= argc) p = NULL;
            else p = argv[optind];
        }

        struct tfile ** file_arr = malloc(sizeof(struct tfile *) * files->length);
        int index = 0;
        foreach(node, files) {
            file_arr[index++] = (struct tfile *)node->value;
        }

        list_free(files);

        qsort(file_arr, index, sizeof(struct tfile *), filecmp);

        int first_directory = index;

        for (int i = 0; i < index; ++i) {
            if (S_ISDIR(file_arr[i]->statbuf.st_mode)) {
                first_directory = i;
                break;
            }
        }

        if (first_directory) {
            display_tfiles(file_arr, first_directory);
        }

        for (int i = first_directory; i < index; ++i) {
            if (i != 0) {
                printf("\n");
            }
            display_dir(file_arr[i]->name);
        }
    }

    return out;
}
Example #29
0
/*
 * Reassemble the chunks together, and write it to the file
 */
void * 
Reassemble(void * args) {
  int chunkcount = 0;

  int fd = -1;
  struct chunk_list * list_head, * p;
  list_head = NULL;

  if (args != NULL) {
    fd = open((char *)args, O_CREAT|O_WRONLY|O_TRUNC, ~(S_ISUID | S_ISGID | S_IXGRP | S_IXUSR | S_IXOTH));
    if (fd < 0) 
      perror("Reassemble open");
  }

  while (1) {
    int f = 0;
    f = 0;
    send_buf_item * item;
    if (tail_reassemble == head_reassemble) {
      break;     
    }
    item = buf_reassemble[tail_reassemble];
    tail_reassemble ++;
    if (tail_reassemble == NUM_BUF_REASSEMBLE) tail_reassemble = 0;

    send_body * body = NULL;
    send_head * head;
    
    switch (item->type) {
    case TYPE_FINGERPRINT:
    case TYPE_COMPRESS:
      body = (send_body *)item->str;
      if (fd == -1) {
        //if havn't get the file header, insert current chunk into the queue
        p = list_insert(list_head, body->cid);
        if (list_head ==NULL || list_head->cid > body->cid) {
          list_head = p;
        }
        p->content = item->content;
        p->cid = body->cid;
        p->len = body->len;
        MEM_FREE(body);
      } else {
          if (body->cid == chunkcount) {
            //if this chunk is in the right order, write it into the file
                          
            if (0 > xwrite(fd, item->content, body->len)) {
              perror("xwrite");
              EXIT_TRACE("xwrite\n");
            }
            chunkcount ++;
            p = list_head;
            while (p != NULL && p->cid == chunkcount) {
              if (0 > xwrite(fd, p->content, p->len)) {
                perror("xwrite");
                EXIT_TRACE("xwrite\n");
              }
              chunkcount ++;
              p = p->next;
            }
            list_head = p;
          } else {
            //if this chunk is out of order, insert it into the list
            p = list_insert(list_head, body->cid);
            if (list_head ==NULL || list_head->cid > body->cid) {
              list_head = p;
            }
            p->content = item->content;
            p->cid = body->cid;
            p->len = body->len;
          }        
          // }
      }
      break;
    case TYPE_HEAD:
      //get file header
      head = (send_head *)item->str;
      if (fd == -1) {
        fd = open(head->filename, O_CREAT|O_WRONLY|O_TRUNC, ~(S_ISUID | S_ISGID | S_IXGRP | S_IXUSR | S_IXOTH));
        if (fd < 0)
          perror("head_open");
      }

      MEM_FREE(head);
      chunkcount = 0;

      p = list_head;
      while (p != NULL && p->cid == chunkcount) {
        if (0 > xwrite(fd, p->content, p->len)) {
          EXIT_TRACE("xwrite\n");
        }
        if (p->content) MEM_FREE(p->content);
        chunkcount ++;
        p = p->next;
      }
      list_head = p;
      
      break;
    }
    
    MEM_FREE(item);
  }

  //write the remaining chunks into the file
  p = list_head;
  while (p != NULL) {
    if (0 > xwrite(fd, p->content, p->len)) {
      EXIT_TRACE("xwrite\n");
    }

    if (p->cid == chunkcount) 
      chunkcount ++;
    else {
      chunkcount = p->cid+1;
    }
    p = p->next;    
  }

  close(fd);
  return NULL;
}
Example #30
0
void test_list(void) {
    int i, arr[MAX];
    int k, s;
    list *l = EMPTY_LIST;

    generate(arr, MAX);

    for (i = 0; i < MAX; i++) {
        l = list_create(arr[i], 0);

        assert(l != EMPTY_LIST);
        assert(l->key == arr[i]);
        assert(list_count(l) == 1);
        assert(list_contains(l, arr[i]));

        l = list_destroy(l);

        assert(l == EMPTY_LIST);
    }
    for (i = 0; i < MAX; i++) {
        l = list_insert(l, arr[i], arr[i]);
        assert(list_contains(l, arr[i]));
    }
    assert(list_ordered(l));
    for (i = 0; i < MAX; i++) {
        l = list_remove_first(l, &k, &s);
        assert(list_ordered(l));
    }
    l = list_destroy(l);

    l = list_insert(l, 5, 0);
    l = list_insert(l, 4, 1);
    l = list_insert(l, 1, 2);
    l = list_insert(l, 2, 6);
    l = list_insert(l, 7, 4);
    l = list_insert(l, 0, 5);
    list_print(l);

    l = list_insert(l, 20, 10);
    l = list_insert(l, 25, -1);
    l = list_insert(l, 30, 3);
    list_print(l);

    l = list_remove_first(l, &k, &s);
    s = 15;
    l = list_insert(l, k, s);
    list_print(l);

    printf("count: %d\n", list_count(l));
    printf("last: %d\n", list_last(l)->key);

    l = list_destroy(l);
}