static int parseArgs(int argc, char **argv, char *argv0, char **path_return, char ***argv_return) { char *path = NULL; char **child_argv = NULL; if(argc <= 0) { char *shell; shell = getenv("SHELL"); if(shell) { path = malloc(strlen(shell) + 1); if(!path) goto bail; strcpy(path, shell); } else { path = malloc(strlen("/bin/sh") + 1); if(!path) goto bail; strcpy(path, "/bin/sh"); } child_argv = malloc(2 * sizeof(char*)); if(!child_argv) goto bail; if(argv0) child_argv[0] = argv0; else child_argv[0] = my_basename(path); child_argv[1] = NULL; } else { path = malloc(strlen(argv[0]) + 1); if(!path) goto bail; strcpy(path, argv[0]); child_argv = malloc((argc + 1) * sizeof(char*)); if(!child_argv) { goto bail; } if(child_argv0) child_argv[0] = argv0; else child_argv[0] = my_basename(argv[0]); memcpy(child_argv + 1, argv + 1, (argc - 1) * sizeof(char*)); child_argv[argc] = NULL; } *path_return = path; *argv_return = child_argv; return 0; bail: if(path) free(path); if(argv) free(argv); return -1; }
void prepare_filename(state *s, TCHAR *fn) { if (s->mode & mode_barename) { if (my_basename(fn)) { print_error_unicode(s,fn,"Unable to shorten filename"); return; } } }
/* Purpose: analyse command line arguments and write them to global struct Params: argc number of arguments argv arguments as array of strings Return: result (0=success, nonzero=failure) */ int parse_options(int argc, char *argv[]) { // initialize the global data structure memset( g, 0, sizeof(struct s_globaldata)); // we use malloc() here for default strings, as we wanna use free() later // when changing the value. free()ing mem in the text segment would be a // bad idea... /* Initialize default values */ #define INIT_DEFAULT_STRING(var, string) \ if ( ((var) = (char*) malloc(strlen(string)+1)) != NULL ) \ strcpy((var), string) INIT_DEFAULT_STRING( g->client_rcfile, CLIENT_RCFILE ); INIT_DEFAULT_STRING( g->client_comdev, CLIENT_COMDEV ); INIT_DEFAULT_STRING( g->server_comdev, SERVER_COMDEV ); INIT_DEFAULT_STRING( g->server_status_file, SERVER_STATUS_FILE ); g->loglevel = LOG_THESE_AND_HIGHER; // log messages with level >= loglevel to logfile // evaluate if we're server or client: // We decide it by looking at the name of the running program if (strstr(my_basename(argv[0]), "server") != NULL) { // the server may be named 'server', 'monitos-server', 'monserver_start', ... INIT_DEFAULT_STRING( g->logfile, SERVER_LOGFILE ); } else if (strstr(my_basename(argv[0]), "client") != NULL) { // the client may be named 'client', 'monitos-client', 'monclient_start', ... INIT_DEFAULT_STRING( g->logfile, CLIENT_LOGFILE ); } else /* this should never happen */ { fprintf(stderr, "Don't know if we're running as server or client, when started as %s", my_basename(argv[0])); INIT_DEFAULT_STRING( g->logfile, "/var/log/monitas.log" ); } #undef INIT_DEFAULT_STRING return 0; }
/* Fills in list of modules if this is the line we want. */ static int add_modules_dep_line(char *line, const char *name, struct list_head *list, const char *dirname) { char *ptr; int len; char *modname, *fullpath; /* Ignore lines without : or which start with a # */ ptr = strchr(line, ':'); if (ptr == NULL || line[strspn(line, "\t ")] == '#') return 0; /* Is this the module we are looking for? */ *ptr = '\0'; modname = my_basename(line); len = strlen(modname); if (strchr(modname, '.')) len = strchr(modname, '.') - modname; if (!modname_equal(modname, name, len)) return 0; /* Create the list. */ if ('/' == line[0]) { /* old style deps - absolute path specified */ add_module(line, ptr - line, list); } else { nofail_asprintf(&fullpath, "%s/%s", dirname, line); add_module(fullpath, strlen(dirname) + 1 + (ptr - line), list); free(fullpath); } ptr++; for (;;) { char *dep_start; ptr += strspn(ptr, " \t"); if (*ptr == '\0') break; dep_start = ptr; ptr += strcspn(ptr, " \t"); if ('/' == dep_start[0]) { /* old style deps */ add_module(dep_start, ptr - dep_start, list); } else { nofail_asprintf(&fullpath, "%s/%s", dirname, dep_start); add_module(fullpath, strlen(dirname) + 1 + (ptr - dep_start), list); free(fullpath); } } return 1; }
void fprintf_fileLine(FILE * fptr, const char *type, const char *func, const char *file, int line_number, const char *format, ...) { //if(MPIdata::get_rank()) return; // writing directly to fptr would avoid limiting the length // of the output string, but by first writing to a string // we achieve thread safety. // // write the message to a string. // const int maxchars = 1024; char error_msg[maxchars+2]; // identify the process and thread char process_thread_str[20]; #ifndef NO_MPI #ifdef _OPENMP snprintf(process_thread_str, 20, "(%d.%d) ", MPIdata::get_rank(), omp_get_thread_num()); #else snprintf(process_thread_str, 20, "(%d)", MPIdata::get_rank()); #endif #else #ifdef _OPENMP snprintf(process_thread_str, 20, "(.%d) ", omp_get_thread_num()); #else snprintf(process_thread_str, 20, ""); #endif #endif char *sptr = error_msg; int chars_so_far=0; va_list args; va_start(args, format); chars_so_far = snprintf(sptr, maxchars, "%s%s %s(), %s:%d: ", process_thread_str, type, func, /*file,*/ my_basename(file), line_number); /* print out remainder of message */ chars_so_far += vsnprintf(sptr+chars_so_far, maxchars-chars_so_far, format, args); va_end(args); sprintf(sptr+chars_so_far, "\n"); // print the message fflush(fptr); fprintf(fptr,error_msg); fflush(fptr); }
static int interface_is(const char* intf_name, const char* driver_name) { /* Return true if this interface is directly implemented by the named * driver. i.e. Will return false for IP aliases and VLANs. */ char link_path[80]; char link_val[80]; int n; sprintf(link_path, "/sys/class/net/%s/device/driver", intf_name); if( (n = readlink(link_path, link_val, sizeof(link_val) - 1)) < 0 ) return 0; link_val[n] = '\0'; return ! strcmp(my_basename(link_val), driver_name); }
static void traverse_directory(const char* dir, void* data, handle_entry_t handle_entry, handle_perror_t handle_perror) { char buffer[PATH_MAX]; struct stat st; DIR *dirp; char* p; // We're chdir() into the directory of "dir", so we need "basename" of dir, to stats on p = my_basename(dir); if(lstat(p,&st) == 0) { handle_entry(data, &st, dir); if(S_ISDIR(st.st_mode)) { char oldcwd[PATH_MAX]; struct dirent* dp; getcwd(oldcwd, sizeof oldcwd); if(chdir(p) != -1) { dirp = opendir("."); if(dirp) { while ((dp = readdir(dirp)) != NULL) { if(strcmp(dp->d_name,".") != 0 && strcmp(dp->d_name,"..") != 0) { strcpy(buffer,dir); strcat(buffer, "/"); strcat(buffer, dp->d_name); traverse_directory(buffer, data, handle_entry, handle_perror); } } closedir(dirp); } else { if(handle_perror) handle_perror(data, "opendir()"); } if(chdir(oldcwd)==-1) { if(handle_perror) handle_perror(data, "chdir-1"); } } else { if(handle_perror) handle_perror(data, "chdir-2"); } } } else { if(handle_perror) handle_perror(data, "stat()"); } }
static void find_newest_ts_worker(void* dataraw, struct stat* st, const char* file) { struct scan_data* data = (struct scan_data*)dataraw; if(S_ISREG(st->st_mode)) { data->ts = MAX(data->ts,st->st_mtime); if(st->st_nlink>1) { hlink_t* n = (hlink_t*)malloc(sizeof(hlink_t)); n->inode = st->st_ino; n->mtime = st->st_mtime; strncpy(n->filename, file, PATH_MAX); list_add((node_t**)data->hardlinks, (node_t*)n); } } else if(S_ISDIR(st->st_mode)) { char* p = my_basename(file); if(strcmp(p,".") != 0 && strcmp(p,"..") != 0) data->ts = MAX(data->ts,st->st_mtime); } }
static void find_newerthan_ts_worker(void* data, struct stat* st, const char* file) { conn_t* cn = ((struct newerthan_data*)data)->cn; time_t ts = ((struct newerthan_data*)data)->ts; if(ts >= st->st_mtime) return; if(S_ISREG(st->st_mode)) { if(st->st_nlink>1) conn_printf(cn, "HLNK %s\n", file); else conn_printf(cn, "FILE %s\n", file); } else if(S_ISDIR(st->st_mode)) { char* p = my_basename(file); if(strcmp(".", p) != 0 && strcmp("..", p) != 0) conn_printf(cn, "DIR %s\n", file); } else if(S_ISLNK(st->st_mode)) { conn_printf(cn, "SLNK %s\n", file); } }
int main (int argc, char *argv[]) { char *code; int i; char *output_file = NULL; char *input_file = NULL; char *include_file = NULL; char *compat_version = VERSION; FILE *output; OrcParseError **errors = NULL; int n_errors = 0; orc_init (); for(i=1;i<argc;i++) { if (strcmp(argv[i], "--header") == 0) { mode = MODE_HEADER; } else if (strcmp(argv[i], "--implementation") == 0) { mode = MODE_IMPL; } else if (strcmp(argv[i], "--test") == 0) { mode = MODE_TEST; } else if (strcmp(argv[i], "--assembly") == 0) { mode = MODE_ASSEMBLY; } else if (strcmp(argv[i], "--parse-only") == 0) { mode = MODE_PARSE; } else if (strcmp(argv[i], "--include") == 0) { if (i+1 < argc) { include_file = argv[i+1]; i++; } else { help(); } } else if (strcmp (argv[i], "--output") == 0 || strcmp(argv[i], "-o") == 0) { if (i+1 < argc) { output_file = argv[i+1]; i++; } else { help(); } } else if (strcmp(argv[i], "--target") == 0 || strcmp(argv[i], "-t") == 0) { if (i+1 < argc) { target = argv[i+1]; i++; } else { help(); } } else if (strcmp(argv[i], "--inline") == 0) { use_inline = TRUE; } else if (strcmp(argv[i], "--no-inline") == 0) { use_inline = FALSE; } else if (strcmp(argv[i], "--internal") == 0) { use_internal = TRUE; } else if (strcmp(argv[i], "--no-internal") == 0) { use_internal = FALSE; } else if (strcmp(argv[i], "--init-function") == 0) { if (i+1 < argc) { init_function = argv[i+1]; i++; } else { help(); } } else if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) { help (); } else if (strcmp(argv[i], "--verbose") == 0 || strcmp(argv[i], "-v") == 0) { verbose = 1; } else if (strcmp(argv[i], "--version") == 0) { fprintf(stderr, "Orc Compiler " PACKAGE_VERSION "\n"); exit (0); } else if (strcmp(argv[i], "--compat") == 0) { if (i+1 < argc) { compat_version = argv[i+1]; i++; } else { help(); } } else if (strcmp(argv[i], "--lazy-init") == 0) { use_lazy_init = TRUE; } else if (strcmp(argv[i], "--no-backup") == 0) { use_backup = FALSE; } else if (strncmp(argv[i], "-", 1) == 0) { fprintf(stderr, "Unknown option: %s\n", argv[i]); exit (1); } else { if (input_file == NULL) { input_file = argv[i]; } else { fprintf(stderr, "More than one input file specified: %s\n", argv[i]); exit (1); } } } if (input_file == NULL) { fprintf(stderr, "No input file specified\n"); exit (1); } if (mode == MODE_ASSEMBLY && orc_target_get_by_name (target) == NULL) { fprintf(stderr, "Unknown target \"%s\"\n", target); exit (1); } if (compat_version) { int major, minor, micro, nano = 0; int n; n = sscanf (compat_version, "%d.%d.%d.%d", &major, &minor, µ, &nano); if (n < 3) { fprintf(stderr, "Unknown version \"%s\"\n", compat_version); exit (1); } compat = ORC_VERSION(major,minor,micro,nano); if (compat < ORC_VERSION(0,4,5,0)) { fprintf(stderr, "Compatibility version \"%s\" not supported. Minimum 0.4.5\n", compat_version); exit (1); } } if (compat >= ORC_VERSION(0,4,11,1)) { use_code = TRUE; } if (output_file == NULL) { switch (mode) { case MODE_IMPL: output_file = "out.c"; break; case MODE_HEADER: output_file = "out.h"; break; case MODE_TEST: output_file = "out_test.c"; break; case MODE_ASSEMBLY: output_file = "out.s"; break; } } code = read_file (input_file); if (!code) { fprintf(stderr, "Could not read input file: %s\n", input_file); exit(1); } orc_parse_code (code, &programs, &n_programs, &errors, &n_errors); if (n_errors > 0) { int i; for (i=0;i<n_errors;i++) { fprintf(stderr, "%s @ %i: error: %s\n", errors[i]->source, errors[i]->line_number, errors[i]->text); } exit (1); } if (programs == NULL) { if (verbose) { fprintf(stderr, "no programs found\n"); } exit(1); } if (verbose) { fprintf(stderr, "%i program%s parsed\n", n_programs, (n_programs > 1) ?"s" :""); } if (mode == MODE_PARSE) { exit (0); } if (init_function == NULL) { init_function = orc_parse_get_init_function (programs[0]); } if (init_function == NULL) { use_lazy_init = TRUE; } output = fopen (output_file, "w"); if (!output) { fprintf(stderr, "Could not write output file: %s\n", output_file); exit(1); } fprintf(output, "\n"); fprintf(output, "/* autogenerated from %s */\n", my_basename(input_file)); fprintf(output, "\n"); if (mode == MODE_IMPL) { fprintf(output, "#ifdef HAVE_CONFIG_H\n"); fprintf(output, "#include \"config.h\"\n"); fprintf(output, "#endif\n"); if (include_file) { fprintf(output, "#include <%s>\n", include_file); } fprintf(output, "\n"); fprintf(output, "%s", orc_target_c_get_typedefs ()); fprintf(output, "\n"); fprintf(output, "#ifndef DISABLE_ORC\n"); fprintf(output, "#include <orc/orc.h>\n"); fprintf(output, "#endif\n"); for(i=0;i<n_programs;i++){ output_code_header (programs[i], output); } if (init_function) { fprintf(output, "\n"); fprintf(output, "void %s (void);\n", init_function); } fprintf(output, "\n"); fprintf(output, "%s", orc_target_get_asm_preamble ("c")); fprintf(output, "\n"); for(i=0;i<n_programs;i++){ output_code (programs[i], output); } fprintf(output, "\n"); if (init_function) { output_init_function (output); fprintf(output, "\n"); } } else if (mode == MODE_HEADER) { char *barrier = get_barrier (output_file); fprintf(output, "#ifndef _%s_\n", barrier); fprintf(output, "#define _%s_\n", barrier); free (barrier); fprintf(output, "\n"); if (include_file) { fprintf(output, "#include <%s>\n", include_file); } fprintf(output, "\n"); fprintf(output, "#ifdef __cplusplus\n"); fprintf(output, "extern \"C\" {\n"); fprintf(output, "#endif\n"); fprintf(output, "\n"); if (init_function) { fprintf(output, "void %s (void);\n", init_function); fprintf(output, "\n"); } fprintf(output, "\n"); if (!use_inline) { fprintf(output, "\n"); fprintf(output, "%s", orc_target_c_get_typedefs ()); for(i=0;i<n_programs;i++){ output_code_header (programs[i], output); } } else { fprintf(output, "\n"); fprintf(output, "#include <orc/orc.h>\n"); fprintf(output, "\n"); for(i=0;i<n_programs;i++){ output_code_execute (programs[i], output, TRUE); } } fprintf(output, "\n"); fprintf(output, "#ifdef __cplusplus\n"); fprintf(output, "}\n"); fprintf(output, "#endif\n"); fprintf(output, "\n"); fprintf(output, "#endif\n"); fprintf(output, "\n"); } else if (mode == MODE_TEST) { fprintf(output, "#include <stdio.h>\n"); fprintf(output, "#include <string.h>\n"); fprintf(output, "#include <stdlib.h>\n"); fprintf(output, "#include <math.h>\n"); if (include_file) { fprintf(output, "#include <%s>\n", include_file); } fprintf(output, "\n"); fprintf(output, "%s", orc_target_c_get_typedefs ()); fprintf(output, "#include <orc/orc.h>\n"); fprintf(output, "#include <orc-test/orctest.h>\n"); fprintf(output, "%s", orc_target_get_asm_preamble ("c")); fprintf(output, "\n"); if (use_backup) { for(i=0;i<n_programs;i++){ fprintf(output, "/* %s */\n", programs[i]->name); output_code_backup (programs[i], output); } } fprintf(output, "\n"); fprintf(output, "static int quiet = 0;\n"); fprintf(output, "static int benchmark = 0;\n"); fprintf(output, "\n"); fprintf(output, "static void help (const char *argv0)\n"); fprintf(output, "{\n"); fprintf(output, " fprintf(stderr, \"Usage:\\n\");\n"); fprintf(output, " fprintf(stderr, \" %%s [OPTION]\\n\", argv0);\n"); fprintf(output, " fprintf(stderr, \"Help Options:\\n\");\n"); fprintf(output, " fprintf(stderr, \" -h, --help Show help options\\n\");\n"); fprintf(output, " fprintf(stderr, \"Application Options:\\n\");\n"); fprintf(output, " fprintf(stderr, \" -b, --benchmark Run benchmark and show results\\n\");\n"); fprintf(output, " fprintf(stderr, \" -q, --quiet Don't output anything except on failures\\n\");\n"); fprintf(output, "\n"); fprintf(output, " exit(0);\n"); fprintf(output, "}\n"); fprintf(output, "\n"); fprintf(output, "int\n"); fprintf(output, "main (int argc, char *argv[])\n"); fprintf(output, "{\n"); fprintf(output, " int error = FALSE;\n"); fprintf(output, " int i;\n"); fprintf(output, "\n"); fprintf(output, " orc_test_init ();\n"); fprintf(output, "\n"); fprintf(output, " for(i=1;i<argc;i++) {\n"); fprintf(output, " if (strcmp(argv[i], \"--help\") == 0 ||\n"); fprintf(output, " strcmp(argv[i], \"-h\") == 0) {\n"); fprintf(output, " help(argv[0]);\n"); fprintf(output, " } else if (strcmp(argv[i], \"--quiet\") == 0 ||\n"); fprintf(output, " strcmp(argv[i], \"-q\") == 0) {\n"); fprintf(output, " quiet = 1;\n"); fprintf(output, " benchmark = 0;\n"); fprintf(output, " } else if (strcmp(argv[i], \"--benchmark\") == 0 ||\n"); fprintf(output, " strcmp(argv[i], \"-b\") == 0) {\n"); fprintf(output, " benchmark = 1;\n"); fprintf(output, " quiet = 0;\n"); fprintf(output, " }\n"); fprintf(output, " }\n"); fprintf(output, "\n"); for(i=0;i<n_programs;i++){ output_code_test (programs[i], output); } fprintf(output, "\n"); fprintf(output, " if (error) {\n"); fprintf(output, " return 1;\n"); fprintf(output, " };\n"); fprintf(output, " return 0;\n"); fprintf(output, "}\n"); } else if (mode == MODE_ASSEMBLY) { fprintf(output, "%s", orc_target_get_asm_preamble (target)); for(i=0;i<n_programs;i++){ output_code_assembly (programs[i], output); } } fclose (output); if (error) { remove (output_file); exit(1); } return 0; }
int main(int argc, char *argv[]) { flickcurl *fc = NULL; int rc = 0; int usage = 0; int help = 0; const char* home; char config_path[1024]; char* photo_id = NULL; const char* prefix_uri = "http://www.flickr.com/photos/"; size_t prefix_uri_len = strlen(prefix_uri); const char *serializer_syntax_name = "ntriples"; raptor_uri* base_uri = NULL; raptor_serializer* serializer = NULL; int request_delay= -1; flickcurl_serializer* fs = NULL; flickcurl_photo* photo = NULL; program = my_basename(argv[0]); flickcurl_init(); rworld = raptor_new_world(); raptor_world_open(rworld); home = getenv("HOME"); if(home) sprintf(config_path, "%s/%s", home, config_filename); else strcpy(config_path, config_filename); while (!usage && !help) { int c; #ifdef HAVE_GETOPT_LONG int option_index = 0; c = getopt_long (argc, argv, GETOPT_STRING, long_options, &option_index); #else c = getopt (argc, argv, GETOPT_STRING); #endif if (c == -1) break; switch (c) { case 0: case '?': /* getopt() - unknown option */ usage = 1; break; case 'd': if(optarg) request_delay = atoi(optarg); break; case 'D': debug = 1; break; case 'h': help = 1; break; case 'o': if(optarg) { if(raptor_world_is_serializer_name(rworld, optarg)) serializer_syntax_name = optarg; else { int i; fprintf(stderr, "%s: invalid argument `%s' for `" HELP_ARG(o, output) "'\n", program, optarg); fprintf(stderr, "Valid arguments are:\n"); for(i = 0; 1; i++) { const raptor_syntax_description *d; d = raptor_world_get_serializer_description(rworld, i); if(!d) break; printf(" %-12s for %s\n", d->names[0], d->label); } usage = 1; break; } } break; case 'v': fputs(flickcurl_version_string, stdout); fputc('\n', stdout); exit(0); } } argv+= optind; argc-= optind; if(!help && argc < 1) usage = 2; /* Title and usage */ if(!help && !argc) { fprintf(stderr, "%s: No photo URI given\n", program); usage = 1; goto usage; } if(usage || help) goto usage; photo_id = argv[0]; if(strncmp(photo_id, prefix_uri, prefix_uri_len)) usage = 1; else { size_t len; photo_id+= prefix_uri_len; len = strlen(photo_id); if(!len) usage = 1; else { if(photo_id[len-1] == '/') photo_id[--len] = '\0'; while(*photo_id && *photo_id != '/') photo_id++; if(!*photo_id) usage = 1; else photo_id++; } } if(usage) { fprintf(stderr, "%s: Argument is not a Flickr photo URI like\n" " http://www.flickr.com/photos/USER/PHOTO/\n", program); goto usage; } serializer = raptor_new_serializer(rworld, serializer_syntax_name); if(!serializer) { fprintf(stderr, "%s: Failed to create raptor serializer type %s\n", program, serializer_syntax_name); return(1); } base_uri = raptor_new_uri(rworld, (const unsigned char*)argv[0]); raptor_serializer_start_to_file_handle(serializer, base_uri, stdout); /* Initialise the Flickcurl library */ fc = flickcurl_new(); if(!fc) { rc = 1; goto tidy; } flickcurl_set_error_handler(fc, my_message_handler, NULL); if(!access((const char*)config_path, R_OK)) { if(flickcurl_config_read_ini(fc, config_path, config_section, fc, flickcurl_config_var_handler)) { rc = 1; goto tidy; } } usage: if(usage) { if(usage>1) { fprintf(stderr, title_format_string, flickcurl_version_string); fputs("Flickcurl home page: ", stderr); fputs(flickcurl_home_url_string, stderr); fputc('\n', stderr); fputs(flickcurl_copyright_string, stderr); fputs("\nLicense: ", stderr); fputs(flickcurl_license_string, stderr); fputs("\n\n", stderr); } fprintf(stderr, "Try `%s " HELP_ARG(h, help) "' for more information.\n", program); rc = 1; goto tidy; } if(help) { int i; printf(title_format_string, flickcurl_version_string); puts("Get Triples from Flickr photos."); printf("Usage: %s [OPTIONS] FLICKR-PHOTO-URI\n\n", program); fputs(flickcurl_copyright_string, stdout); fputs("\nLicense: ", stdout); puts(flickcurl_license_string); fputs("Flickcurl home page: ", stdout); puts(flickcurl_home_url_string); fputs("\n", stdout); puts(HELP_TEXT("d", "delay DELAY ", "Set delay between requests in milliseconds")); puts(HELP_TEXT("D", "debug ", "Print lots of output")); puts(HELP_TEXT("h", "help ", "Print this help, then exit")); puts(HELP_TEXT("o", "output FORMAT ", "Set output format to one of:")); for(i = 0; 1; i++) { const raptor_syntax_description* d; d = raptor_world_get_serializer_description(rworld, i); if(!d) break; if(!strcmp(d->names[0], serializer_syntax_name)) printf(" %-15s %s (default)\n", d->names[0], d->label); else printf(" %-15s %s\n", d->names[0], d->label); } #ifdef HAVE_RAPTOR printf(" via Raptor %s serializers\n", raptor_version_string); #else puts(" via internal RDF serializer"); #endif puts(HELP_TEXT("v", "version ", "Print the flickcurl version")); rc = 0; goto tidy; } if(request_delay >= 0) flickcurl_set_request_delay(fc, request_delay); fs = flickcurl_new_serializer(fc, serializer, &flickrdf_serializer_factory); if(!fs) { fprintf(stderr, "%s: Failed to create Flickcurl serializer\n", program); goto tidy; } photo = flickcurl_photos_getInfo(fc, photo_id); if(!photo) goto tidy; if(debug) fprintf(stderr, "%s: Photo with URI %s ID %s has %d tags\n", program, photo->uri, photo->id, photo->tags_count); rc = flickcurl_serialize_photo(fs, photo); tidy: if(photo) flickcurl_free_photo(photo); if(fs) flickcurl_free_serializer(fs); if(fc) flickcurl_free(fc); if(serializer) raptor_free_serializer(serializer); if(base_uri) raptor_free_uri(base_uri); if(rworld) raptor_free_world(rworld); flickcurl_finish(); return(rc); }
int main(int argc, char *argv[]) { flickcurl *fc = NULL; int rc = 0; int usage = 0; int help = 0; int read_auth = 1; int i; const char* home; char config_path[1024]; char** methods = NULL; int count = 0; flickcurl_init(); program = my_basename(argv[0]); home = getenv("HOME"); if(home) sprintf(config_path, "%s/%s", home, config_filename); else strcpy(config_path, config_filename); while (!usage && !help) { int c; #ifdef HAVE_GETOPT_LONG int option_index = 0; c = getopt_long (argc, argv, GETOPT_STRING, long_options, &option_index); #else c = getopt (argc, argv, GETOPT_STRING); #endif if (c == -1) break; switch (c) { case 0: case '?': /* getopt() - unknown option */ usage = 1; break; case 'h': help = 1; break; case 'v': fputs(flickcurl_version_string, stdout); fputc('\n', stdout); exit(0); } } if(help) goto help; if(argc != 1) { fprintf(stderr, "%s: Extra arguments given\n", program); usage = 1; } if(usage) { if(usage>1) { fprintf(stderr, title_format_string, flickcurl_version_string); fputs("Flickcurl home page: ", stderr); fputs(flickcurl_home_url_string, stderr); fputc('\n', stderr); fputs(flickcurl_copyright_string, stderr); fputs("\nLicense: ", stderr); fputs(flickcurl_license_string, stderr); fputs("\n\n", stderr); } fprintf(stderr, "Try `%s " HELP_ARG(h, help) "' for more information.\n", program); rc = 1; goto tidy; } help: if(help) { printf(title_format_string, flickcurl_version_string); puts("List Flickr API methods by reflection."); printf("Usage: %s [OPTIONS]\n\n", program); fputs(flickcurl_copyright_string, stdout); fputs("\nLicense: ", stdout); puts(flickcurl_license_string); fputs("Flickcurl home page: ", stdout); puts(flickcurl_home_url_string); fputs("\n", stdout); puts(HELP_TEXT("h", "help ", "Print this help, then exit")); puts(HELP_TEXT("v", "version ", "Print the flickcurl version")); rc = 0; goto tidy; } /* Initialise the Flickcurl library */ fc = flickcurl_new(); if(!fc) { rc = 1; goto tidy; } flickcurl_set_error_handler(fc, my_message_handler, NULL); if(read_auth && !access((const char*)config_path, R_OK)) { if(flickcurl_config_read_ini(fc, config_path, config_section, fc, flickcurl_config_var_handler)) { rc = 1; goto tidy; } } methods = flickcurl_reflection_getMethods(fc); if(!methods) { fprintf(stderr, "%s: getMethods failed\n", program); rc = 1; goto tidy; } for(i = 0; methods[i]; i++) ; count = i; fprintf(stderr, "%s: Found %d API methods\n", program, count); /* it seems to be sorted when returned but ensure it anyway */ qsort(methods, count, sizeof(char*), compare_strings); for(i = 0; methods[i]; i++) { fputs((const char*)methods[i], stdout); fputc('\n', stdout); } tidy: if(methods) { for(i = 0; methods[i]; i++) free(methods[i]); free(methods); methods = NULL; } if(fc) flickcurl_free(fc); flickcurl_finish(); return(rc); }
int hash_file(state *s, TCHAR *fn) { size_t fn_length; char *sum; TCHAR *my_filename, *msg; FILE *handle; handle = _tfopen(fn,_TEXT("rb")); if (NULL == handle) { print_error_unicode(s,fn,"%s", strerror(errno)); return TRUE; } if ((sum = (char *)malloc(sizeof(char) * FUZZY_MAX_RESULT)) == NULL) { fclose(handle); print_error_unicode(s,fn,"%s", strerror(errno)); return TRUE; } if ((msg = (TCHAR *)malloc(sizeof(TCHAR) * (MAX_STATUS_MSG + 2))) == NULL) { free(sum); fclose(handle); print_error_unicode(s,fn,"%s", strerror(errno)); return TRUE; } if (MODE(mode_verbose)) { fn_length = _tcslen(fn); if (fn_length > MAX_STATUS_MSG) { // We have to make a duplicate of the string to call basename on it // We need the original name for the output later on my_filename = _tcsdup(fn); my_basename(my_filename); } else my_filename = fn; _sntprintf(msg, MAX_STATUS_MSG-1, _TEXT("Hashing: %s%s"), my_filename, _TEXT(BLANK_LINE)); _ftprintf(stderr,_TEXT("%s\r"), msg); if (fn_length > MAX_STATUS_MSG) free(my_filename); } fuzzy_hash_file(handle,sum); prepare_filename(s,fn); display_result(s,fn,sum); if (find_file_size(handle) > SSDEEP_MIN_FILE_SIZE) s->found_meaningful_file = true; s->processed_file = true; fclose(handle); free(sum); free(msg); return FALSE; }
int main(int argc, char *argv[]) { unsigned int i; long int ret; unsigned long len; void *file; char *filename, *options = strdup(""); char *p, *progname = argv[0]; if (!options) { fprintf(stderr, "insmod: can't allocate memory: %s\n", strerror(errno)); exit(1); } p = my_basename(argv[0]); if (argv[1] && (streq(argv[1], "--version") || streq(argv[1], "-V"))) { puts(PACKAGE " version " VERSION); exit(0); } /* * kdi-addition */ if (argv[1] && streq(argv[1], "-K")) { flag_kdi = 1; flag_use_kdi = 1; argv++; argc--; kdi_name = NOFAIL(strdup(argv[1])); argv++; argc--; } if (argv[1] && streq(argv[1], "-F")) { flag_kdi = 1; flag_inject_faults = 1; argv++; argc--; } if (argv[1] && streq(argv[1], "-T")) { flag_kdi = 1; flag_use_kdi_shadow = 1; argv++; argc--; shadow_type = NOFAIL(strdup(argv[1])); argv++; argc--; } if (argv[1] && streq(argv[1], "-N")) { flag_kdi = 1; flag_use_kdi = 1; flag_clobber_kdi = 1; argv++; argc--; clobber_module_name = NOFAIL(strdup(argv[1])); argv++; argc--; } /* * kdi-end */ /* Ignore old options, for backwards compat. */ while (argv[1] && (streq(argv[1], "-p") || streq(argv[1], "-s") || streq(argv[1], "-f"))) { argv++; argc--; } filename = argv[1]; if (!filename) print_usage(progname); /* Rest is options */ for (i = 2; i < argc; i++) { options = realloc(options, strlen(options) + 1 + strlen(argv[i]) + 1); if (!options) { fprintf(stderr, "insmod: can't allocate memory: %s\n", strerror(errno)); exit(1); } strcat(options, argv[i]); strcat(options, " "); } file = grab_file(filename, &len); if (!file) { fprintf(stderr, "insmod: can't read '%s': %s\n", filename, strerror(errno)); exit(1); } /* * kdi-addition */ if (flag_kdi) { if (init_kdi() != 0) exit(1); struct kdi_uargs *kdi_opts = malloc(sizeof(struct kdi_uargs)); kdi_opts->use_kdi = flag_use_kdi; kdi_opts->use_kdi_shadow = flag_use_kdi_shadow; kdi_opts->inject_faults = flag_inject_faults; kdi_opts->clobber_kdi = flag_clobber_kdi; if (kdi_name) strncpy(kdi_opts->kdi_name, kdi_name, 100); if (clobber_module_name) strncpy(kdi_opts->clobber_module_name, clobber_module_name, 100); if (shadow_type) strncpy(kdi_opts->shadow_type, shadow_type, 100); ret = syscall(SYS_kdi_init_module, file, len, options, kdi_opts); } else ret = init_module(file, len, options); /* * kdi-end */ if (ret != 0) { fprintf(stderr, "insmod: error inserting '%s': %li %s\n", filename, ret, moderror(errno)); } free(file); /* * kdi-addition */ if (ret != 0 && flag_created_kdi == 1) syscall(SYS_kdi_delete_kdi, kdi_name); /* * kdi-end */ if (ret != 0) exit(1); exit(0); }
int main(int argc, char *argv[]) { flickcurl *fc = NULL; int rc = 0; int usage = 0; int help = 0; int read_auth = 1; int i; const char* home; char config_path[1024]; int request_delay= -1; char section[50]; size_t section_len; char** methods = NULL; flickcurl_init(); program = my_basename(argv[0]); home = getenv("HOME"); if(home) sprintf(config_path, "%s/%s", home, config_filename); else strcpy(config_path, config_filename); while (!usage && !help) { int c; #ifdef HAVE_GETOPT_LONG int option_index = 0; c = getopt_long (argc, argv, GETOPT_STRING, long_options, &option_index); #else c = getopt (argc, argv, GETOPT_STRING); #endif if (c == -1) break; switch (c) { case 0: case '?': /* getopt() - unknown option */ usage = 1; break; case 'd': if(optarg) request_delay = atoi(optarg); break; case 'h': help = 1; break; case 'v': fputs(flickcurl_version_string, stdout); fputc('\n', stdout); exit(0); } } if(help) goto help; if(argc < 2) { fprintf(stderr, "%s: No API section given\n", program); usage = 1; } if(usage) { if(usage>1) { fprintf(stderr, title_format_string, flickcurl_version_string); fputs("Flickcurl home page: ", stderr); fputs(flickcurl_home_url_string, stderr); fputc('\n', stderr); fputs(flickcurl_copyright_string, stderr); fputs("\nLicense: ", stderr); fputs(flickcurl_license_string, stderr); fputs("\n\n", stderr); } fprintf(stderr, "Try `%s " HELP_ARG(h, help) "' for more information.\n", program); rc = 1; goto tidy; } help: if(help) { printf(title_format_string, flickcurl_version_string); puts("Generate C code from Flickr API by reflection."); printf("Usage: %s [OPTIONS] command args...\n\n", program); fputs(flickcurl_copyright_string, stdout); fputs("\nLicense: ", stdout); puts(flickcurl_license_string); fputs("Flickcurl home page: ", stdout); puts(flickcurl_home_url_string); fputs("\n", stdout); puts(HELP_TEXT("d", "delay DELAY ", "Set delay between requests in milliseconds")); puts(HELP_TEXT("h", "help ", "Print this help, then exit")); puts(HELP_TEXT("v", "version ", "Print the flickcurl version")); rc = 0; goto tidy; } /* Initialise the Flickcurl library */ fc = flickcurl_new(); if(!fc) { rc = 1; goto tidy; } flickcurl_set_error_handler(fc, my_message_handler, NULL); if(read_auth && !access((const char*)config_path, R_OK)) { if(read_ini_config(config_path, config_section, fc, my_set_config_var_handler)) { fprintf(stderr, "%s: Failed to read config filename %s: %s\n", program, config_path, strerror(errno)); rc = 1; goto tidy; } } if(request_delay >= 0) flickcurl_set_request_delay(fc, request_delay); strcpy(section, "flickr."); strcpy(section+7, argv[1]); /* allow old format commands to work */ for(i = 0; section[i]; i++) { if(section[i] == '-') section[i] = '.'; } if(!strncmp(section, "flickr.flickr", 13)) strcpy(section, section+7); section_len = strlen(section); fprintf(stderr, "%s: section '%s'\n", program, section); methods = flickcurl_reflection_getMethods(fc); if(!methods) { fprintf(stderr, "%s: getMethods failed\n", program); rc = 1; goto tidy; } fprintf(stdout, "/* -*- Mode: c; c-basic-offset: 2 -*-\n" " *\n" " * %s-api.c - Flickr %s.* API calls\n" " *\n", argv[1], section); fprintf(stdout, " * Copyright (C) 2010, David Beckett http://www.dajobe.org/\n" " * \n" " * This file is licensed under the following three licenses as alternatives:\n" " * 1. GNU Lesser General Public License (LGPL) V2.1 or any newer version\n" " * 2. GNU General Public License (GPL) V2 or any newer version\n" " * 3. Apache License, V2.0 or any newer version\n" " * \n" " * You may not use this file except in compliance with at least one of\n" " * the above three licenses.\n" " * \n" " * See LICENSE.html or LICENSE.txt at the top of this package for the\n" " * complete terms and further detail along with the license texts for\n" " * the licenses in COPYING.LIB, COPYING and LICENSE-2.0.txt respectively.\n" " * \n" " */\n" "\n" "#include <stdio.h>\n" "#include <string.h>\n" "#include <stdarg.h>\n" "\n" "#ifdef HAVE_CONFIG_H\n" "#include <config.h>\n" "#endif\n" "\n" "#ifdef HAVE_STDLIB_H\n" "#include <stdlib.h>\n" "#undef HAVE_STDLIB_H\n" "#endif\n" "#ifdef HAVE_UNISTD_H\n" "#include <unistd.h>\n" "#endif\n" "\n" "#include <flickcurl.h>\n" "#include <flickcurl_internal.h>\n" "\n" "\n" ); for(i = 0; methods[i]; i++) { flickcurl_method* method; char* method_name; char function_name[100]; int c, j; int is_write = 0; if(strncmp(methods[i], section, section_len)) continue; method = flickcurl_reflection_getMethodInfo(fc, methods[i]); if(!method) { fprintf(stderr, "%s: getMethodInfo(%s) failed\n", program, methods[i]); rc = 1; break; } method_name = method->name; if( strstr(method_name, ".add") || strstr(method_name, ".create") || strstr(method_name, ".delete") || strstr(method_name, ".edit") || strstr(method_name, ".remove") || strstr(method_name, ".set") ) is_write = 1; strcpy(function_name, "flickcurl_"); for(j = 0; (c = methods[i][j+7]); j++) { if(c == '.') c = '_'; function_name[j+10] = c; } function_name[j+10] = '\0'; fprintf(stdout, "/**\n * %s:\n", function_name); /* fixed arguments */ fprintf(stdout, " * @fc: flickcurl context\n"); if(method->args_count) { int argi; for(argi = 0; method->args[argi]; argi++) { flickcurl_arg* arg = method->args[argi]; if(!strcmp(arg->name, "api_key")) continue; fprintf(stdout, " * @%s: %s", arg->name, arg->description); if(arg->optional) { fputs((IS_INT_ARG(arg)? " (or < 0)" : " (or NULL)"), stdout); } fputc('\n', stdout); } } fprintf(stdout, " * \n" " * %s\n" " *\n" " * Implements %s (%s)\n", method->description, method->name, flickcurl_version_string ); fprintf(stdout, " * \n" " * Return value: non-0 on failure\n" " **/\n" ); fprintf(stdout, "int\n%s(flickcurl* fc", function_name); if(method->args_count) { int argi; for(argi = 0; method->args[argi]; argi++) { flickcurl_arg* arg = method->args[argi]; if(!strcmp(arg->name, "api_key")) continue; if(IS_INT_ARG(arg)) { fprintf(stdout, ", int %s", arg->name); } else { fprintf(stdout, ", const char* %s", arg->name); } } } fprintf(stdout, ")\n{\n"); fprintf(stdout, " const char* parameters[%d][2];\n" " int count = 0;\n" " xmlDocPtr doc = NULL;\n" " xmlXPathContextPtr xpathCtx = NULL; \n" " void* result = NULL;\n", 6+method->args_count); if(method->args_count) { int argi; for(argi = 0; method->args[argi]; argi++) { flickcurl_arg* arg = method->args[argi]; if(IS_INT_ARG(arg)) { fprintf(stdout, " char %s_str[10];\n", arg->name); } } } fputs( " \n", stdout); if(method->args_count) { int argi; int print_or = 0; fprintf(stdout, " if("); for(argi = 0; method->args[argi]; argi++) { flickcurl_arg* arg = method->args[argi]; if(!strcmp(arg->name, "api_key")) continue; if(!arg->optional) { if(print_or) fprintf(stdout, " || "); fprintf(stdout, "!%s", arg->name); print_or = 1; } } fprintf(stdout, ")\n" " return 1;\n" "\n"); } if(method->args_count) { int argi; for(argi = 0; method->args[argi]; argi++) { flickcurl_arg* arg = method->args[argi]; if(!strcmp(arg->name, "api_key")) continue; if(arg->optional) { if(IS_INT_ARG(arg)) { fprintf(stdout, " if(%s >= 0) {\n" " sprintf(%s_str, \"%%d\", %s);\n" " parameters[count][0] = \"%s\";\n" " parameters[count++][1]= %s_str;\n" " }\n", arg->name, arg->name, arg->name, arg->name, arg->name); continue; } fprintf(stdout, " if(%s) {\n", arg->name); } fprintf(stdout, " parameters[count][0] = \"%s\";\n" " parameters[count++][1]= %s;\n", arg->name, arg->name); if(arg->optional) { fprintf(stdout, " }\n" ); } } } fprintf(stdout, "\n" " parameters[count][0] = NULL;\n" "\n" ); fprintf(stdout, " if(flickcurl_prepare(fc, \"%s\", parameters, count))\n" " goto tidy;\n" "\n", method->name); if(is_write) fprintf(stdout, " flickcurl_set_write(fc, 1);\n" " flickcurl_set_data(fc, (void*)\"\", 0);\n" "\n" ); fprintf(stdout, " doc = flickcurl_invoke(fc);\n" " if(!doc)\n" " goto tidy;\n" "\n" "\n" " xpathCtx = xmlXPathNewContext(doc);\n" " if(!xpathCtx) {\n" " flickcurl_error(fc, \"Failed to create XPath context for document\");\n" " fc->failed = 1;\n" " goto tidy;\n" " }\n" "\n" " result = NULL; /* your code here */\n" "\n" " tidy:\n" " if(xpathCtx)\n" " xmlXPathFreeContext(xpathCtx);\n" "\n" " if(fc->failed)\n" " result = NULL;\n" "\n" " return (result == NULL);\n" "}\n" "\n" "\n"); flickcurl_free_method(method); } tidy: if(methods) { for(i = 0; methods[i]; i++) free(methods[i]); free(methods); methods = NULL; } if(fc) flickcurl_free(fc); flickcurl_finish(); return(rc); }
/*{{{ main() */ int main (int argc, char *argv[]) { int i; char *val, **cmd_argv = NULL; /* "WINDOWID=\0" = 10 chars, UINT_MAX = 10 chars */ static char windowid_string[20], *display_string; for (i = 0; i < argc; i++) { if (!strcmp (argv[i], "-e")) { argc = i; argv[argc] = NULL; if (argv[argc + 1] != NULL) { cmd_argv = (argv + argc + 1); if (cmd_argv[0] != NULL) rs_iconName = rs_title = my_basename (cmd_argv[0]); } break; } } rs_name = my_basename (argv[0]); /* * Open display, get options/resources and create the window */ if ((display_name = getenv ("DISPLAY")) == NULL) display_name = ":0"; get_options (argc, argv); Xdisplay = XOpenDisplay (display_name); if (!Xdisplay) { print_error ("can't open display %s", display_name); exit (EXIT_FAILURE); } extract_resources (Xdisplay, rs_name); /* * set any defaults not already set */ if (!rs_title) rs_title = rs_name; if (!rs_iconName) rs_iconName = rs_name; if (!rs_saveLines || (TermWin.saveLines = atoi (rs_saveLines)) < 0) TermWin.saveLines = SAVELINES; /* no point having a scrollbar without having any scrollback! */ if (!TermWin.saveLines) Options &= ~Opt_scrollBar; #ifdef PRINTPIPE if (!rs_print_pipe) rs_print_pipe = PRINTPIPE; #endif if (!rs_cutchars) rs_cutchars = CUTCHARS; #ifndef NO_BOLDFONT if (rs_font[0] == NULL && rs_boldFont != NULL) { rs_font[0] = rs_boldFont; rs_boldFont = NULL; } #endif for (i = 0; i < NFONTS; i++) { if (!rs_font[i]) rs_font[i] = def_fontName[i]; #ifdef KANJI if (!rs_kfont[i]) rs_kfont[i] = def_kfontName[i]; #endif } #ifdef XTERM_REVERSE_VIDEO /* this is how xterm implements reverseVideo */ if (Options & Opt_reverseVideo) { if (!rs_color[fgColor]) rs_color[fgColor] = def_colorName[bgColor]; if (!rs_color[bgColor]) rs_color[bgColor] = def_colorName[fgColor]; } #endif for (i = 0; i < NRS_COLORS; i++) if (!rs_color[i]) rs_color[i] = def_colorName[i]; #ifndef XTERM_REVERSE_VIDEO /* this is how we implement reverseVideo */ if (Options & Opt_reverseVideo) { const char *name; /* swap foreground/background colors */ name = rs_color[fgColor]; rs_color[fgColor] = rs_color[bgColor]; rs_color[bgColor] = name; name = def_colorName[fgColor]; def_colorName[fgColor] = def_colorName[bgColor]; def_colorName[bgColor] = name; } #endif /* convenient aliases for setting fg/bg to colors */ color_aliases (fgColor); color_aliases (bgColor); #ifndef NO_CURSORCOLOR color_aliases (cursorColor); color_aliases (cursorColor2); #endif /* NO_CURSORCOLOR */ #ifndef NO_BOLDUNDERLINE color_aliases (colorBD); color_aliases (colorUL); #endif /* NO_BOLDUNDERLINE */ Create_Windows (argc, argv); scr_reset (); /* initialize screen */ Gr_reset (); /* reset graphics */ /* add scrollBar, do it directly to avoid resize() */ scrollbar_mapping (Options & Opt_scrollBar); #ifdef DEBUG_X XSynchronize (Xdisplay, True); XSetErrorHandler ((XErrorHandler) abort); #else XSetErrorHandler ((XErrorHandler) xerror_handler); #endif #ifdef DISPLAY_IS_IP /* Fixup display_name for export over pty to any interested terminal * clients via "ESC[7n" (e.g. shells). Note we use the pure IP number * (for the first non-loopback interface) that we get from * network_display(). This is more "name-resolution-portable", if you * will, and probably allows for faster x-client startup if your name * server is beyond a slow link or overloaded at client startup. Of * course that only helps the shell's child processes, not us. * * Giving out the display_name also affords a potential security hole */ val = display_name = network_display (display_name); if (val == NULL) #endif /* DISPLAY_IS_IP */ val = XDisplayString (Xdisplay); if (display_name == NULL) display_name = val; /* use broken `:0' value */ i = strlen (val); display_string = MALLOC ((i + 9) * sizeof (char), "display_string"); sprintf (display_string, "DISPLAY=%s", val); sprintf (windowid_string, "WINDOWID=%u", (unsigned int) TermWin.parent); /* add entries to the environment: * @ DISPLAY: in case we started with -display * @ WINDOWID: X window id number of the window * @ COLORTERM: terminal sub-name and also indicates its color * @ TERM: terminal name */ putenv (display_string); putenv (windowid_string); if (Xdepth <= 2) { putenv ("COLORTERM=" COLORTERMENV "-mono"); putenv ("TERM=" TERMENV); } else { #ifdef XPM_BACKGROUND putenv ("COLORTERM=" COLORTERMENV "-xpm"); #else putenv ("COLORTERM=" COLORTERMENV); #endif #ifdef DEFINE_XTERM_COLOR putenv ("TERM=" TERMENV "-color"); #else putenv ("TERM=" TERMENV); #endif } init_command (cmd_argv); main_loop (); /* main processing loop */ return EXIT_SUCCESS; }
static void proto_handle_get(conn_t* cn, const char* line) { struct stat st; // Reject filenames with just "." and ".." if(memcmp(line, ".\0", 2) == 0 || memcmp(line, "..\0", 3) == 0) { conn_printf(cn, "ERROR Protocol violation (%d)\n", __LINE__); conn_abort(cn); return; } if(lstat(line,&st) == 0) { if(S_ISREG(st.st_mode)) { int fd; md5_state_t md5_state; md5_init(&md5_state); char buffer[PATH_MAX]; ssize_t size; char md5str[33]; char modestr[11]; #ifdef O_NOATIME if((fd = open(line,O_RDONLY|O_NOATIME))==-1) { #else if((fd = open(line,O_RDONLY))==-1) { #endif conn_perror(cn, "WARNING open()"); conn_printf(cn, "WARNING Can't open file: %s\n", line); return; } // Calcuate MD5 { unsigned char md5bin[16]; while((size = read(fd, buffer, sizeof buffer))) md5_append(&md5_state, (unsigned char*)buffer, size); md5_finish(&md5_state, (unsigned char*)md5bin); if(lseek(fd, SEEK_SET, 0)==-1) { conn_perror(cn, "ERROR lseek()"); conn_abort(cn); return; } md5bin2str(md5bin, md5str); } mode2str(st.st_mode, modestr); conn_printf(cn, "PUT %ld %s %s %ld %ld %ld %s\n", (long int)st.st_size, md5str, modestr, st.st_atime, st.st_ctime, st.st_mtime, line); while((size = read(fd, buffer, sizeof buffer))) conn_write(cn, buffer, size); close(fd); } else if(S_ISDIR(st.st_mode)) { char modestr[11]; mode2str(st.st_mode, modestr); conn_printf(cn, "MKDIR %s %ld %ld %ld %s\n", modestr, st.st_atime, st.st_ctime, st.st_mtime, line); } else if(S_ISLNK(st.st_mode)) { char buffer[PATH_MAX]; conn_printf(cn, "SLNK %s\n", line); ssize_t l; if((l=readlink(line, buffer, sizeof buffer))==-1) { conn_perror(cn, "WARNING readlink()"); return; } buffer[l] = '\0'; conn_printf(cn, "%s\n", buffer); } else { conn_printf(cn, "WARNING Ignored %s\n", line); } } } static void proto_handle_put(conn_t* cn, const char* line) { const char* delim = " "; char* saveptr = NULL; char* token; char* ptr = (char*)line; int c = 0; ssize_t size = 0; mode_t mode = 0; time_t mtime = 0; time_t ctime = 0; time_t atime = 0; char* name = NULL; char* md5 = NULL; while((token = strtok_r(ptr, delim, &saveptr))) { switch(c) { case 0: size = atol(token); break; case 1: md5 = token; break; case 2: mode = str2mode(token); break; case 3: atime = atol(token); break; case 4: ctime = atol(token); break; case 5: mtime = atol(token); break; case 6: name = token; break; } c++; ptr = NULL; } if(c != 7) { conn_printf(cn, "ERROR Protocol violation (%d)\n", __LINE__); conn_abort(cn); return ; } int fd = creat(name, O_CREAT|O_TRUNC); if(fd == -1) { conn_perror(cn, "WARNING creat()"); return; } if(chmod(name,mode)==-1) { perror("WARNING chmod()"); } struct utimbuf t; t.actime = atime; t.modtime = mtime; if(utime(name,&t)==-1) { perror("WARNING utime"); } // CONTENT int bytes_left = size; int r; md5_state_t md5_state; unsigned char md5bin[16]; char md5str[33]; md5_init(&md5_state); while(!cn->abort && bytes_left) { if(cn->rbuf_len == 0) (void)conn_read(cn); r = MIN(bytes_left, cn->rbuf_len); if(r) { write(fd, cn->rbuf, r); md5_append(&md5_state, (unsigned char*)cn->rbuf, r); conn_shift(cn,r); bytes_left -= r; } assert(bytes_left >= 0); } close(fd); md5_finish(&md5_state, (unsigned char*)md5bin); md5bin2str(md5bin, md5str); // Check md5 if(strcmp(md5str,md5)!=0) { // Mismatch! conn_printf(cn, "WARNING %s md5-mismatch (%s <-> %s), removing file\n", name, md5str, md5); if(unlink(name)==-1) { perror("WARNING: unlink()"); } } else { struct utimbuf t; t.actime = atime; t.modtime = mtime; if(utime(name,&t)==-1) { perror("utime"); conn_printf(cn, "WARNING Can't timestamp on directory: %s\n", name); } // md5 is fine conn_printf(cn, "GET %s\n", name); } } static void proto_handle_slnk(conn_t* cn, const char* line) { char curdir[PATH_MAX]; // read next line to get target char target[PATH_MAX]; if(!conn_readline(cn, target, sizeof target)) return; getcwd(curdir, sizeof curdir); // Make sure it dosnt exist unlink(line); if(chdir(my_dirname(line))==-1) { conn_perror(cn, "WARNING chdir()"); return; } if(symlink(target, my_basename(line))==-1) { conn_perror(cn, "ERROR symlink()"); conn_abort(cn); return; } chdir(curdir); conn_printf(cn, "GET %s\n", line); }